我不确定我是否在主题上正确地提出了问题,但我会尽力向我解释我的问题.
我有以下ContactUsModel,它是Homeviewmodel的一部分,更好地说是单个模型中的嵌套模型类
public class ContactUsDataModel { public string ContactName { get; set; } public string ContactEmail { get; set; } public string ContactMessage { get; set; } public string ContactPhone { get; set; } }
public class Homeviewmodel { /*My other models goes here*/ public ContactUsDataModel CUDModel { get; set; } }
现在在Index.cshtml视图中,我强烈创建了一个表单视图,如下所示:
@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,placeholder = "Message *" }) <input type="submit" id="submit" class="contact submit" value="Send message"> }
我做ajax Post如下:
$('#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,//success success: function (result) { //Code here },error: function (xhr,responseText,status) { //Code here } }); });
在控制器中我试图接收如下:
public JsonResult ContactPost(ContactUsDataModel model) { var name=model.ContactName; //null /*Fetch the data and save it and return Json*/ //model is always null }
由于某种原因,上述模型始终为null.但是,如果我将模型称为Homeviewmodel模型而不是如下所示的控制器参数中的ContactUsDataModel模型,则此方法有效:
public JsonResult ContactPost(Homeviewmodel model) { var name=model.CUDModel.ContactName; //gets value /*Fetch the data and save it and return Json*/ //Model is filled. }
My question here is even though I fill
model
of type
ContactUsDataModel
in the view I am getting it asnull
if I refer
directly,butContactUsModel
which is insideHomeviewmodel
gets
filled. Doesn’t type of model matter here. Is the hierarchy its
referred is necessary while fetching in controller?