问题
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