admin管理员组文章数量:1312993
I'm trying to figure out a way to pass the entire class from my View to a Controller with Javascript/AJAX.
I know the following Ajax code can be used to pass just the ID but can I pass the entire model ?
@model User
$.ajax(
{
type: "POST",
url: "\User\",
data: @model.id,
success:
reloadPage()
});
I saw the following solution while searching: Is there a way to pass a "C#" object to a controller via AJAX?
Can I simply do this instead ? :
@model User
$.ajax(
{
type: "POST",
url: "\User\",
data: @model,
success:
reloadPage()
});
Will this work ? How safe ? What's the best way ?
I'm trying to figure out a way to pass the entire class from my View to a Controller with Javascript/AJAX.
I know the following Ajax code can be used to pass just the ID but can I pass the entire model ?
@model User
$.ajax(
{
type: "POST",
url: "\User\",
data: @model.id,
success:
reloadPage()
});
I saw the following solution while searching: Is there a way to pass a "C#" object to a controller via AJAX?
Can I simply do this instead ? :
@model User
$.ajax(
{
type: "POST",
url: "\User\",
data: @model,
success:
reloadPage()
});
Will this work ? How safe ? What's the best way ?
Share Improve this question edited May 23, 2017 at 12:20 CommunityBot 11 silver badge asked Apr 6, 2012 at 1:39 InspiredByInspiredBy 4,3206 gold badges44 silver badges67 bronze badges4 Answers
Reset to default 4Check out the JavascriptSerializer.Serialize() method. So something like this:
@model User
$.ajax({
type: "POST",
url: "\User\",
data: JSON.parse(@(new JavascriptSerializer().Serialize(Model))),
success: reloadPage
});
Essentially, this serializes your model to a JSON string, which is then parsed client side back into a JS object, which is then passed into the AJAX request. When the request hits the server, MVC model binding handles constructing an instance of the model based off the JSON object.
Note that JSON.parse is not supported in older versions of IE. You can get json2.js to shim the method for IE.
Although not best practice, if there is no other way to get this data then you may pass the data via tempdata
View:
@{
TempData["myModel"] = Model;
}
Controller:
var myModel = TempData["myModel"];
TempData.Remove("myModel");
Create a Json object with the same properties as original object, Give the Json object name as controller parameter name. Pass the Json object to Controller Using AJAX request
MVC model binding will takecare of remaining things
try using the serialize (jQuery)
eg.
$.ajax({
type: "POST",
url: "\User\",
data: $(form).serialize(),
success: reloadPage()
});
本文标签: cHow to pass an entire object to a controller with JavasctiptAJAX in MVCStack Overflow
版权声明:本文标题:c# - How to pass an entire object to a controller with JavasctiptAJAX in MVC? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741838541a2400358.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论