jquery - MVC3 使用 JQuery Ajax 将 ViewModel 传递给 Controller ​​方法

标签 jquery ajax asp.net-mvc-3

我正在尝试使用 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/

相关文章:

javascript - 如何检测子页面中打开的打印预览模式?

javascript - PHP 和 AJAX : How to produce a heat map based on number values?

asp.net-mvc-3 - _AppStart 执行时无法创建存储范围

c# - ASP.NET MVC 3 使用升序、降序选项自定义排序 WebGrid

jquery - 有没有用于表格固定标题和排序的 jQuery 插件?

javascript - Jquery改变颜色条件

javascript - 无法调用 jquery 插件方法

javascript - img 高度占浏览器窗口的百分比

javascript - jQuery ajax 成功方法在 ie8 中有效,但在 ie9 中无效?

asp.net-mvc-3 - Html 到 pdf asp.net mvc