使用 Jquery Ajax 将模型从视图传递到控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18102560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing Model from view to controller with Jquery Ajax
提问by udayangana
I'm try to pass my model values from View to Controller by using ajax JQuery
. In my controller that model is shown as null
.
我尝试使用 ajax 将我的模型值从 View 传递到 Controller JQuery
。在我的控制器中,该模型显示为null
.
Controller already called from ajax method, but the problem is object in the controller is showing as null
.
控制器已从 ajax 方法调用,但问题是控制器中的对象显示为null
.
This is Simple structure of model:
这是模型的简单结构:
public class Invoice
{
public Invoice(InvoiceHeader invHeader, List<InvoiceItems> InvItmem)
{
this.invHeader = invHeader;
this.InvItmem = InvItmem;
}
public InvoiceHeader invHeader { get; private set; }
public List<InvoiceItems> InvItmem { get; private set; }
}
This is structure of Controller:
这是控制器的结构:
[HttpPost]
public ActionResult InsertItems(List<Invoice> invoice)
{
//List<InvoiceItems> asd = new List<InvoiceItems>();
//asd = invoice.();
return Json(true, JsonRequestBehavior.AllowGet);
}
This is View:
这是视图:
@model BeetaTechModel.Invoice
@{
ViewBag.Title = "Index";
var val = Json.Encode(Model);
}
<h2>Index</h2>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
// var val = Json.Encode(Model);
var check = @Html.Raw(val);
$.ajax({
type: 'POST',
url: "Invoice/InsertItems",
data: '{info:' + JSON.stringify(check) + '}' ,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
alert(data);
}
});
});
});
</script>
@{Html.RenderPartial("InvoiceHeader", Model.invHeader);}
@{Html.RenderPartial("InvoiceItems", Model.InvItmem);}
<input type="submit" id="btnSubmit" value="Log In" />
回答by Darin Dimitrov
You have 4 issues with your code.
您的代码有 4 个问题。
The first one is in your AJAX call which must look like this:
$.ajax({ url: 'Invoice/InsertItems', type: 'POST', data: JSON.stringify(check), contentType: 'application/json; charset=utf-8', success: function (data) { alert(data); } });
The second issue is that you subscribed to the
.click
event of a submit button without canceling the default action of this button. So if this button is inside a form, when you click it, the browser will POST the form to the server and redirect away to the action of the form leaving no time for your AJAX call to ever execute. So make sure you are canceling the default action of the button:$("#btnSubmit").click(function (e) { e.preventDefault(); ... your AJAX call comes here });
The third issue is that your
Invoice
model doesn't have a default (parameterless) constructor meaning that you cannot use it as argument to a controller action without writing a custom model binder because the default model binder wouldn't know how to instantiate it.And the fourth issue is that both the
invHeader
andInvItmem
properties of yourInvoice
model do not have public setters meaning that the JSON serializer will be unable to set their values. So make sure you have fixed your Invoice model:public class Invoice { public InvoiceHeader InvHeader { get; set; } public List<InvoiceItems> InvItmem { get; set; } }
第一个在您的 AJAX 调用中,它必须如下所示:
$.ajax({ url: 'Invoice/InsertItems', type: 'POST', data: JSON.stringify(check), contentType: 'application/json; charset=utf-8', success: function (data) { alert(data); } });
第二个问题是您订阅
.click
了提交按钮的事件,而没有取消该按钮的默认操作。因此,如果此按钮位于表单内,当您单击它时,浏览器会将表单发布到服务器并重定向到表单的操作,从而没有时间执行 AJAX 调用。因此,请确保您取消了按钮的默认操作:$("#btnSubmit").click(function (e) { e.preventDefault(); ... your AJAX call comes here });
第三个问题是您的
Invoice
模型没有默认(无参数)构造函数,这意味着您不能在不编写自定义模型绑定器的情况下将其用作控制器操作的参数,因为默认模型绑定器不知道如何实例化它。第四个问题是模型的属性
invHeader
和InvItmem
属性Invoice
都没有公共设置器,这意味着 JSON 序列化程序将无法设置它们的值。因此,请确保您已修复您的发票模型:public class Invoice { public InvoiceHeader InvHeader { get; set; } public List<InvoiceItems> InvItmem { get; set; } }
回答by Sergio
data: '{info:'
doesn't match model name:public ActionResult InsertItems(List<Invoice> invoice)
- Probably you need default constructor for model for proper deserialization.
- Check if your ajax data could be deserialized in
List<Invoice>
data: '{info:'
与型号名称不匹配:public ActionResult InsertItems(List<Invoice> invoice)
- 可能您需要模型的默认构造函数以进行正确的反序列化。
- 检查您的ajax数据是否可以反序列化
List<Invoice>