c# – 模型在控制器中接收数据时是否保持其结构?
我不确定我是否在主题上正确地提出了问题,但我会尽力向我解释我的问题.
我有以下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. }
解决方法
好吧,如果你生成的< input> name是CUDModel.ContactName而不是简单的ContactName,默认的Model-Binder将无法绑定它.
幸运的是,您可以使用带有前缀的[Bind]属性: public JsonResult ContactPost([Bind(Prefix="CUDModel")]ContactUsDataModel model) { // ... } 见MSDN (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |