我想使用$ .POST或$ .AJAX实现创建(插入)屏幕。
注意:代码无需AJAX调用即可正常工作..它已经存在..现在我需要进行ajax调用并保存而无需回发。我写了下面的代码:
在提交点击事件时,代码如下:
$.ajax( { url: '@Url.Action("CreateProduct","ProductManagement")', dataType: 'json', contentType: 'application/json; charset=utf-8', type: 'post', data: $('frm').serialize(), success: function () { alert('s'); }, error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); } } ); });
在服务器端:
[HttpPost] public JsonResult CreateProduct(FormCollection frm) { manager.ProductManager m = new manager.ProductManager(); // m.InsertProduct(new common.DTO.ProductDTO() { Id = id, ProductName = ProductName, Description = Description, Cost = cost, ProductTypeId = 5 }); return Json("'result':'success'", JsonRequestBehavior.AllowGet); }
问题是,每次它都会调用操作,但在frm参数param 上找不到数据。我也试图保持-视图模型ProductViewModel vm作为参数,但是它没有用..只是给了我null值。同样,在ajax调用中,它成功但是。唯一的问题是控制器的动作上没有任何内容。
frm
ProductViewModel vm
HTML如下:
@using (Html.BeginForm("CreateProduct", "ProductManagement", FormMethod.Post, new { id = "frm" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <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>
请指导我这里出了什么问题。
谢谢
对于ID选择器,您必须使用带有ID的“#”。
这将起作用:
$.ajax( { url: '@Url.Action("CreateProduct","ProductManagement")', dataType: 'json', contentType: 'application/json; charset=utf-8', type: 'post', data: $('this').serialize(), OR $('#frm').serialize(), <----------------- success: function () { alert('s'); }, error: function (e1, e2, e3) { alert(e2); alert(e1 + ' ' + e2 + ' ' + e3); alert('failure event'); } } );
或者尝试一下:
var form = $('#frm'); $.ajax({ cache: false, async: true, dataType: 'json', contentType: 'application/json; charset=utf-8', type: "POST", url: form.attr('action'), data: form.serialize(), success: function (data) { alert(data); } });