有没有办法通过一个" C#"反对通过AJAX控制器? [英] Is there a way to pass a "C#" object to a controller via AJAX?
问题描述
这是很简单的传递一个字符串到通过jQuery AJAX控制器的动作,但有可能要序列化一组变量成一个对象,将其发送到控制器,并有控制其识别为一个对象?
It's simple enough to pass a string to a controller action via jQuery ajax, but is it possible to serialize a group of variables into an object, send it to the controller, and have the controller recognize it as an object?
例如:
在服务器上,你有一个类的OBJ这样:
In the server, you have a class Obj as such:
class Obj{
string a; int b; double c;
}
和控制器,你有一种方法,它期待一个OBJ对象
And in the controller, you have a method that is expecting an Obj object
public JsonResult UpdateObj(Obj obj){
//stuff
}
有jQuery的办法序列化一些JavaScript的VAR到一个类的OBJ,然后通过AJAX后发送到MVC控制器动作?
Is there a way in Jquery to serialize some JavaScript vars into a class Obj and then send it to an MVC controller action via an AJAX post?
推荐答案
当然,让我们假设你有一个强类型的视图:
Sure, let's suppose that you have a strongly typed 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>
和控制器中的动作:
public ActionResult SomeAction(Obj obj)
{
...
}
就在这个的OBJ此言一出,使其具有公共属性,而不是某些领域:
Just a remark about this Obj, make it have public properties instead of some fields:
public class Obj
{
public string A { get; set; }
public int B { get; set; }
public double C { get; set; }
}
这篇关于有没有办法通过一个&QUOT; C#&QUOT;反对通过AJAX控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!