将实体信息传递给ASP.NET MVC 3中的jquery对话框的最有效方法

时间:2012-08-12 03:39:39

标签: jquery asp.net-mvc json jquery-ui jquery-dialog

我有这个ASP.NET MVC 3页面,我在模型中循环一组对象,基本上我会在每个实体信息/显示旁边有一个按钮,允许用户在jQuery中编辑该实体UI对话框。

我坚持的是找到将实体信息传递给jquery对话框的最佳方法。

我正在考虑使用许多data-x属性,一个用于对象的每个属性,或者只是将实体JSON表示存储在单个data-x属性中。

传递信息并在jQuery UI对话框中分配信息的最佳方法是什么?如果有人有任何样本都很棒。感谢。

1 个答案:

答案 0 :(得分:0)

您可以考虑做的一件事是设置一个控制器,负责将服务作为JSON字符串发出,然后在您的按钮单击事件(启动jQuery对话框)中调用该服务。要做到这一点,您需要JSON序列化程序的帮助,例如jsonfx(我个人最喜欢的),您可以在VS中将其作为nuget包下载。

例如,如果您正在调用单个实体:

public class ServiceController : Controller
    {
        public ActionResult GetFoo(FormCollection fc)
        {
            var json = MyFooGetter(fc["fooId"]); //Id of the object
            var writer = new JsonWriter();
            return Content(writer.Write(json), "application/json");
        }
}

在客户端,您可以这样请求此服务:

$.post("/service/GetFoo", {fooId: "1"}, function (response) {
        //Do stuff with your response object which is a traversable JSON version of your entity(ies).
        //Example:
        var h1 = $("<h1>");
        h1.html(response.title);
        $("document").append(h1);
    });

实体集合的另一个例子:

public class ServiceController : Controller
    {
        public ActionResult GetFooCollection()
        {
            var json = MyFooCollectionGetter(); 
            var writer = new JsonWriter();
            return Content(writer.Write(json), "application/json");
       }
}

在客户端,您可以这样请求此服务:

$.post("/service/GetFooCollection", function (response) {
        //Do stuff with your response object which is a traversable JSON version of your entity(ies).
        //Example:
       $.each(response,function(i){
          alert(response[i].title);
       });
    });
祝你好运!