我不确定我是否在主题上正确地提出了问题,但我会尽力向我解释我的问题.
我有以下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; } }
我在HomeViewModel中获取此模型,如下所示:
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?
解决方法
好吧,如果你生成的< input> name是CUDModel.ContactName而不是简单的ContactName,默认的Model-Binder将无法绑定它.
幸运的是,您可以使用带有前缀的[Bind]属性:
public JsonResult ContactPost([Bind(Prefix="CUDModel")]ContactUsDataModel model) { // ... }
见MSDN
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。