How to pass strong-typed model as data param to jquery ajax post?

筅森魡賤 提交于 2019-12-21 21:35:23

问题


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");
        }
    });

回答1:


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.



来源:https://stackoverflow.com/questions/9379862/how-to-pass-strong-typed-model-as-data-param-to-jquery-ajax-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!