作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
通过 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/
我是一名优秀的程序员,十分优秀!