gpt4 book ai didi

asp.net-mvc-3 - 有没有办法通过 AJAX 将 "C#"对象传递给 Controller ​​?

转载 作者:行者123 更新时间:2023-12-03 23:00:57 24 4
gpt4 key购买 nike

通过 jQuery ajax 将字符串传递给 Controller ​​操作很简单,但是是否可以将一组变量序列化为一个对象,将其发送到 Controller ,并让 Controller 将其识别为对象?

例如:

在服务器中,您有一个 Obj 类:

class Obj{
string a; int b; double c;
}

在 Controller 中,您有一个需要 Obj 对象的方法

public JsonResult UpdateObj(Obj obj){
//stuff
}

Jquery 中有没有办法将一些 JavaScript 变量序列化为 Obj 类,然后通过 AJAX post 将其发送到 MVC Controller 操作?

最佳答案

当然,假设您有一个强类型 View :

@model Obj

<script type="text/javascript">
// Serialize the model into a javascript variable
var model = @Html.Raw(Json.Encode(Model));

// post the javascript variable back to the controller
$.ajax({
url: '/home/someAction',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.serialize(model),
success: function(result) {
// TODO: do something with the results
}
});
</script>

并在 Controller 操作中:

public ActionResult SomeAction(Obj obj)
{
...
}

关于这个 Obj 的注释,让它具有公共(public)属性而不是某些字段:

public class Obj
{
public string A { get; set; }
public int B { get; set; }
public double C { get; set; }
}

关于asp.net-mvc-3 - 有没有办法通过 AJAX 将 "C#"对象传递给 Controller ​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6766984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com