如何使用jquery在MVC中发布viewmodel

时间:2014-08-03 16:30:31

标签: c# jquery ajax asp.net-mvc asp.net-mvc-4

我没有使用Form元素。 我没有使用过表单,因为我不想回发..请指导我如何进行ajax调用,以便能够获得$ .ajax将viewmodel发布到控制器的动作方法? 我的表格如下:

HTML:

  @model comp.learn.data.Models.ProductViewModel

 @{
ViewBag.Title = "Create";
}

 <h2>Create</h2>


<fieldset>
    <legend>ProductViewModel</legend>
    <div id="CreateDiv">
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Cost)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Cost)
            @Html.ValidationMessageFor(model => model.Cost)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductTypeId)
        </div>
        <div class="editor-field">
            @Html.DropDownList("ProductTypeId", "Choose item")
            @Html.ValidationMessageFor(model => model.ProductTypeId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductTypeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductTypeName)
            @Html.ValidationMessageFor(model => model.ProductTypeName)
        </div>
    </div>
    <p>
        <input type="submit" value="Create" id="btnSubmit" />
    </p>

</fieldset>


<div>
  @Html.ActionLink("Back to List", "Index")
</div>

的jQuery / JavaScript的:

         $.ajax(
                {
                    url: '@Url.Action("CreateProduct","ProductManagement")',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    type: 'post',
                    cache: false,
                    data: ///what should i write here ,
                    success: function (data) { alert('final'); },
                    error: function (f1, f2, f3) { alert(f3); }
                });

2 个答案:

答案 0 :(得分:11)

您应该手动从输入中收集数据并构造与您的C#模型类对应的JSON对象。例如,如果您在操作方法中等待ProductViewModel对象,则可以按照以下示例进行操作:

var myData = {
    productName: $('#ProductName').val(),
    cost: $('#Cost').val(),
    // .. and so on
};

$.ajax({
    data: JSON.stringify(myData),
    // .. the other ajax options
});

如果你有表单元素,那就更容易了。只需使用jQuery选择表单并调用serialize方法。数据将被编码为字符串以供提交。格式为application/x-www-form-urlencoded; charset=UTF-8,也就是$ .ajax默认值,您无需指定它。例如:

var myData = $('#myFormId').serialize();
$.ajax({
    data: myData,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    //..Other ajax options
});

答案 1 :(得分:1)

您需要两件事才能实现这一目标:

首先:包装您的表单标记视图中的所有输入/数据元素,如下所示:

@using(Html.BeginForm())
{
    //exitsing html stuff
}

第二:在Ajax请求中,使用 serializeArray() 对一组表单元素进行编码,并将其传递到以下数据中:

$.ajax(
{
    url: '@Url.Action("CreateProduct","ProductManagement")',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    type: 'post',
    cache: false,
    data: $('form').serializeArray(),
    success: function (data) { alert('final'); },
    error: function (f1, f2, f3) { alert(f3); }
});

这将解决您的问题。