问题描述
我试图表单的数据传递到使用JQuery的Ajax我的控制器的方法,但我不知道你是怎么做这是我的视图模型为空,当我使用调试器的控制器端。
I'm trying to pass a form's data to my controller method using JQuery Ajax, but I'm not sure how you do this as my ViewModel is null when I use debugger on the Controller Side.
我的视图模型为:
public class PremisesViewModel
{
public string createPremisesErrorMessage { get; set; }
public string updatePremisesErrorMessage { get; set; }
public SelectList listOfCounties = Initialise.countiesSelectList;
public Premise premises { get; set; }
}
其中premises是在我的数据库实体/表。
where premises is an entity/table in my database.
该表单包含在premises表中的字段。
The form contains the fields in the Premises table.
在我的javascript函数我这样做:
In my javascript function I do this:
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');
}
})
然而,当我检查我的方法视图模型的参数,它是空:
However, when I check the viewModel parameter in my method, it is null:
[HttpPost]
public JsonResult Create(PremisesViewModel pvm)
{
return null;
}
这是如何映射这使得视图模型是正确绑定任何想法。谢谢
Any ideas on how to map this so that the viewmodel is bound correctly.Thanks
推荐答案
您的JSON格式完全一样的模型类。
Your JSON format exactly same as your model class.
当前例如
public class PremisesViewModel
{
public string createPremisesErrorMessage { get; set; }
public string updatePremisesErrorMessage { get; set; }
public SelectList listOfCounties = Initialise.countiesSelectList;
public Premise premises { get; set; }
}
您JSON像
var premisesViewModel = {
createPremisesErrorMessage : $('#premises_PremisesDescription').val(),
updatePremisesErrorMessage: $('#premises_OrdnanceSurveyReference').val(),
premises : {Define more properties here as per your Premise structure}
}
这篇关于MVC3传递视图模型使用JQuery Ajax来控制器的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!