如何通过强类型的模型参数数据jQuery的AJAX张贴? [英] How to pass strong-typed model as data param to jquery ajax post?

查看:145
本文介绍了如何通过强类型的模型参数数据jQuery的AJAX张贴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来传递我的强类型的视图模型作为数据参数,这个jQuery AJAX调用?我见过的每一个例子,我不得不例如建立自己的JSON {属性:值等}。是不是有一些甜美的JS佣工/ codz格兰做到这一点?

  $。阿贾克斯({
        网址:'/ myController的/ myaction',
        输入:POST,
        数据:或其可==这里
        的contentType:应用/ JSON的;字符集= UTF-8,
        成功:函数(data.success){
            警报(数据);
        },
        错误:函数(){
            警报(错误);
        }
    });


解决方案

您可以编写一个使用的帮手的JavaScriptSerializer

 公共静态IHtmlString的toJSON<&的TModel GT;(这与的HtmlHelper LT;的TModel> HTML,对象数据)
{
    VAR串行=新的JavaScriptSerializer();
    返回新HtmlString(serializer.Serialize(数据));
}

和调用它:

  @ Html.ToJson(MYDATA的)

我也写了一个助手来做到这一点(你可以只偷code或使用的NuGet包):

https://github.com/paultyng/FluentJson.NET

您可以创建一个剃刀JSON视图像这样(注意淘汰赛扩展方法):

  @ JsonObject.Create()
        .AddProperty(名称,值)
        .AddProperty(childObject,C = GT; {
            .AddProperty(childProperty,值2)
        })

这将产生JSON与此类似:

  {名:价值,childObject:{childProperty:值2}}

它采用了串行JSON.NET,而不是建于一身,你可以很容易地调整其code到自己的用途和内置的之一,如果你不想要一个额外的依赖。

Is there an easy way to pass my strong-typed view model as the data parameter to this jquery ajax call? Every example I've seen, I'd have to build the json myself e.g. { Property : "Value", etc. }. Isn't there some luscious js helpers/codz teh do this?

$.ajax({
        url: '/mycontroller/myaction',
        type: 'POST',
        data: <== Here
        contentType: 'application/json; charset=utf-8',
        success: function (data.success) {
            alert(data);
        },
        error: function () {
            alert("error");
        }
    });

解决方案

You could write a helper that used the JavascriptSerializer:

public static IHtmlString ToJson<TModel>(this HtmlHelper<TModel> html, object data)
{
    var serializer = new JavaScriptSerializer();
    return new HtmlString(serializer.Serialize(data));
}

And call it like:

@Html.ToJson(myData)

I also wrote a helper to do this (you could just steal the code or use the Nuget package):

https://github.com/paultyng/FluentJson.NET

You can create JSON in a Razor view like this (note the Knockout extension methods):

    @JsonObject.Create()
        .AddProperty("name", "value")
        .AddProperty("childObject", c => {
            .AddProperty("childProperty", "value2")
        })

This would produce JSON similar to this:

{"name":"value","childObject":{"childProperty":"value2"}}

It uses the JSON.NET serializer, not the built in one, you could easily adapt its code to your own uses and the built in one if you didn't want an additional dependency.

这篇关于如何通过强类型的模型参数数据jQuery的AJAX张贴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆