I am not sure whether the question was formulated correctly in the topic, but I will try to explain everything that I have.
I have below ContactUsModel , which is part of HomeViewModel , better say that Nested Model Class in one model
public class ContactUsDataModel { public string ContactName { get; set; } public string ContactEmail { get; set; } public string ContactMessage { get; set; } public string ContactPhone { get; set; } }
and I get this model specified in HomeViewModel as below:
public class HomeViewModel { public ContactUsDataModel CUDModel { get; set; } }
Now in the Index.cshtml I strongly create the form view, as shown below:
@model ProjectName.Models.HomeViewModel <!--I have other views for other models--> @using (Html.BeginForm("ContactPost", "Home", FormMethod.Post, new { id = "contactform" })) { @Html.TextBoxFor(m => m.CUDModel.ContactName, new { @class="contact col-md-6 col-xs-12", placeholder="Your Name *" }) @Html.TextBoxFor(m => m.CUDModel.ContactEmail, new { @class = "contact noMarr col-md-6 col-xs-12", placeholder = "E-mail address *" }) @Html.TextBoxFor(m => m.CUDModel.ContactPhone, new { @class = "contact col-md-12 col-xs-12", placeholder = "Contact Number (optional)" }) @Html.TextAreaFor(m=>m.CUDModel.ContactMessage, new { @class = "contact col-md-12 col-xs-12", placeholder = "Message *" }) <input type="submit" id="submit" class="contact submit" value="Send message"> }
I am doing ajax Publish as below:
$('#contactform').on('submit', function (e) { e.preventDefault(); var formdata = new FormData($('.contact form').get(0)); $.ajax({ url: $("#contactform").attr('action'), type: 'POST', data: formdata, processData: false, contentType: false,
and in the controller I tried to get it as shown below:
public JsonResult ContactPost(ContactUsDataModel model) { var name=model.ContactName;
For some reason, the above model is always null . But it works if I attribute the model as HomeViewModel model instead of HomeViewModel model ContactUsDataModel model to the controller parameter, as shown below:
public JsonResult ContactPost(HomeViewModel model) { var name=model.CUDModel.ContactName;
My question is here, although I populate a model type ContactUsDataModel in the view, I get it as null if I refer directly, but the HomeViewModel that is inside the HomeViewModel gets populated. This is not the type of model. Is the hierarchy required when assembling in the controller?