我正在尝试使用 JQuery Ajax 将表单的数据传递到我的 Controller 方法,但我不确定如何执行此操作,因为当我在 Controller 端使用调试器时,我的 ViewModel 为空。
我的 View 模型是:
public class PremisesViewModel
{
public string createPremisesErrorMessage { get; set; }
public string updatePremisesErrorMessage { get; set; }
public SelectList listOfCounties = Initialise.countiesSelectList;
public Premise premises { get; set; }
}
其中前提是我的数据库中的实体/表。
该表单包含 Premises 表中的字段。
在我的 javascript 函数中我这样做:
var premisesViewModel = {
Id: 0,
PremisesDescription: $('#premises_PremisesDescription').val(),
OrdnanceSurveyReference: $('#premises_OrdnanceSurveyReference').val(),
PartRestrictedNotes: $('#premises_PartRestrictedNotes').val(),
NatureOfPremises: $('#premises_NatureOfPremises').val(),
AddressLine1: $('#premises_AddressLine1').val(),
AddressLine2: $('#premises_AddressLine2').val(),
Town: $('#premises_Town').val(),
CountyId: $('#premises_CountyId').val(),
Postcode: $('#premises_Postcode').val()
}
alert(form.serialize);
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(premisesViewModel),
success: function (data) {
alert('done');
}
})
但是,当我检查方法中的 viewModel 参数时,它为 null:
[HttpPost]
public JsonResult Create(PremisesViewModel pvm)
{
return null;
}
关于如何映射它以便正确绑定(bind) View 模型的任何想法。 谢谢
最佳答案
如果您想从表单的绑定(bind) View 模型自动构建模型,您可以使用此答案 https://stackoverflow.com/a/1186309 中的代码正确序列化为 JSON 对象。
然后您需要将其作为字符串传递给您的 $.ajax 调用。总而言之,与您原来的非常相似。像这样的东西:
var premisesViewModel = $('form').serializeObject();
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(premisesViewModel),
success: function (data) {
alert('done');
}
});
很奇怪的是,没有核心函数可以转换为 JSON 对象,但是就这样了。
关于jquery - MVC3 使用 JQuery Ajax 将 ViewModel 传递给 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9871365/