如何在MVC中使用jquery发布视图模型
本文关键字:布视图 视图 模型 jquery MVC | 更新日期: 2023-09-27 18:16:23
我如何用jQuery做一个ajax调用,以便我可以使用$。ajax张贴ViewModel到控制器的动作方法?
我没有使用Form
元素,因为我不想回发…
到目前为止,我的表单是这样的:
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); }
});
您应该手动从输入中收集数据并构建与您的c#模型类对应的JSON对象。例如,如果您在操作方法中等待ProductViewModel对象,您可以遵循以下示例:
var myData = {
productName: $('#ProductName').val(),
cost: $('#Cost').val(),
// .. and so on
};
$.ajax({
data: JSON.stringify(myData),
// .. the other ajax options
});
如果有form元素就更容易了。只需用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
});
要做到这一点,需要满足两个条件:
First:将in form标签视图中的所有input/data元素换行,如下所示:
@using(Html.BeginForm())
{
//exitsing html stuff
}
Second:在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); }
});