Gur*_*Rao 6 c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-5
我不确定我是否在主题上正确地提出了问题,但我会尽力向我解释我的问题.
我在下面是ContactUsModel其中的一部分HomeViewModel,更好的说是单一的嵌套模型类model
public class ContactUsDataModel
{
public string ContactName { get; set; }
public string ContactEmail { get; set; }
public string ContactMessage { get; set; }
public string ContactPhone { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我Model将在HomeViewModel下面提到这个:
public class HomeViewModel
{
/*My other models goes here*/
public ContactUsDataModel CUDModel { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在在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, new { @class = "contact col-md-12 col-xs-12", placeholder = "Message *" })
<input type="submit" id="submit" class="contact submit" value="Send message">
}
Run Code Online (Sandbox Code Playgroud)
我ajax发帖如下:
$('#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
}
});
});
Run Code Online (Sandbox Code Playgroud)
在控制器中我试图接收如下:
public JsonResult ContactPost(ContactUsDataModel model)
{
var name=model.ContactName; //null
/*Fetch the data and save it and return Json*/
//model is always null
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,上述模型总是如此null.但是,如果我引用modelas HomeViewModel model而不是ContactUsDataModel model如下所示的控制器参数,这是有效的:
public JsonResult ContactPost(HomeViewModel model)
{
var name=model.CUDModel.ContactName; //gets value
/*Fetch the data and save it and return Json*/
//Model is filled.
}
Run Code Online (Sandbox Code Playgroud)
我在这里的问题是即使我在视图中填写
model类型ContactUsDataModel我得到它就像null我直接引用,但ContactUsModel内部HomeViewModel被填充.这里没有型号的类型.在控制器中获取时,是否需要引用它的层次结构?
好吧,如果您生成的<input>名称不是CUDModel.ContactNamesimple ContactName,则默认的 Model-Binder 将无法绑定它。
幸运的是,您可以使用[Bind]带有前缀的属性:
public JsonResult ContactPost([Bind(Prefix="CUDModel")]ContactUsDataModel model)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
参见MSDN