JSON.Stringify ASP.NET MVC - asp.net-mvc

I am trying to post data in JSON format to a .NET MVC Controller like this.
$.ajax({
type: 'POST',
url: 'http://mvc.tester.local/Home/NameConverter',
data: JSON.stringify({ convertermodel.InputName: obj.currentTarget.value }),
contentType: 'application/json'
});
But Javascript complains about the JSON.Stringify() bit.
The convertermodel.InputName to be exact.
The thing is I actually need this JSON data name to be that way i.e. have the same name as a property in my model; in order to take advantage of reflection for automatic binding.
This is my model:
public class NamesViewModel
{
public NameConverterModel convertermodel = new NameConverterModel();
}
and the sub Class
public class NameConverterModel
{
private string _inputName = "";
public string InputName
{
get { return _inputName; }
set { _inputName = value; }
}
}
How can I solve this please ?
I hope I am clear enough.

You would need your JSON to be of the structure like this:
{"convertermodel" : {
"InputName" : obj.currentTarget.value
}
}
Your JSON representation of your object needs to reflect the appropriate nesting that your object model that you're trying to model in the client-side requires. So defining your JSON by nesting your hierarchy at one level won't work -- you need to create objects of objects like you did in your C# code.

Related

use specific field as a backbone's model data

I'm retrieving a json and want to use a field(don't know the right term) in the json to initialize backbone model after fetch.
It seems I have to implement parse function, but how?
1) You need to define defaults object on your model setting up properties you want to populate from a request; 2) then you need to filter (those) necessary fields and construct new object in the model's parse method:
var model = Backbone.Model.extend({
defaults: {
swordType: null
},
parse: function(data) {
// filter what you need
var swordTypeValue = null;
if(data.hasOwnProperty('swordType')) {
swordTypeValue = data.swordType;
}
// construct attributes from it
return { swordType: swordTypeValue };
}
});

mvc4 webapi custom json serializer for specific type

I know MVC4 uses NewtonSoft Json de/serialization. I was wondering how I can exclude a property on serialization to client, without using any of the data annotations like JsonIgnore/DataMemberIngore etc (the assembly is used elsewhere and can't be changed. Can I implement a custom formatter/JsonSerializerSettings/Dynamic ContractResolver etc for a specific object type and then filter out a specific property name?
Any help much appreciated.
Edit. Came up with the following as a first attempt. If anyone has a more elegant solution please let me know...
public class DynamicContractResolver : DefaultContractResolver
{
public DynamicContractResolver()
{
}
protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, Newtonsoft.Json.MemberSerialization.Fields);
if (type == typeof(SomeType))
{
var matchedProp = properties.Where(v=> v.PropertyName=="SomeProperty").FirstOrDefault();
if (matchedProp!=null)
{
properties.Remove(matchedProp);
}
}
return properties;
}
}
Plumbed into global.asax:
HttpConfiguration config = GlobalConfiguration.Configuration;
JsonSerializerSettings serializerSetting = new JsonSerializerSettings
{
ContractResolver = new DynamicContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
};
config.Formatters.JsonFormatter.SerializerSettings = serializerSetting;
Regards
Phil
This is solvable with a proper overriding
Override a Json function(s) that is in the MVC Controller class.
In this class you can customize the data. (with another mapping,
with reflection, ...)
Create a custom JsonResult class, just override the default one. You
are also able to override there the default serialization which is
going on there.
Now:
You can exclude this data when you already have a JSON
serialized string ... This would be the easiest option. Basically just string operations.
On the other hand you will also be able to call a custom NewtonSoft
serialization and you can do there whatever you want ... Even use custom serializations.

Return JSON containing javascript functions from ASP.NET MVC

I have a JSON-like data structure (which I don't want to change) that is currently generated by an .aspx file spitting out javascript. It looks like .NET ate jQuery for lunch, and then vomited...
I'd like to rewrite the entire thing to an MVC controller action that returns a JsonResult, basically by building up an anonymous object and pass it to return Json(data).
However, I can't figure out how to construct the C# object when some of the properties on the JSON object I want to build are actually JavaScript functions. How do I do that?
Example:
I want to create the following JSON-like object:
{
id: 55,
name: 'john smith',
age: 32,
dostuff: aPredefinedFunctionHandle,
isOlderThan: function(other) { return age > other.age }
}
You see that I want to be able to specify both function handles to JavaScript functions that I have defined elsewhere (in .js files, usually) and that I want to define new inline functions.
I know how to build part of that object in C#:
var data = new { id = 55, name = "john smith", age = 32 };
return Json(data);
Is there any good way to do also the rest of it?
There is no built-in type in .NET that maps to javascript function. So you may have to create a custom type that represents a function and you have to do the serialization yourself.
Something like this..
public class JsFunction
{
public string FunctionString{get; set;}
}
new
{
id = 55,
name = 'john smith',
age = 32,
dostuff = new JsFunction{ FunctionString = "aPredefinedFunctionHandle" },
isOlderThan = new JsFunction{ FunctionString = "function(other) { return age >
other.age" }
}
On serialization you may have to check the type of the value and write the FunctionString directly into the response without double-quotes.
JSON explicitly excludes functions because it isn't meant to be a JavaScript-only data structure (despite the JS in the name). So we should not include function name in JSON
JSON excludes functions. It sounds like you want to encapsulate your data into a class. How about something like the following:
function Person(data) {
this.id = data.id;
this.name = data.name;
this.age = data.age;
this.isOlderThan = function(other) { return this.age > other.age };
}

Json isn't returning a result that is accessible as an array

I'm having troubles reading a Json result back from a controller method...
I have this method in my controller:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetCurrent()
{
IList<string> profile = new List<string>();
profile.Add("-1");
profile.Add("Test");
profile.Add("");
return this.Json(profile);
}
And it is being called by this jquery ajax post:
$.post("/Profile/GetCurrent", function(profile) { profileCompleteOpen(profile); }, "json");
and the javascript function called on the post's callback:
function profileCompleteOpen(profile) {
alert(profile);
alert(profile[0]);
}
The result of the first alert shows the array like this:
["-1","Test",""]
But the result of the second alert shows this:
[
rather than
-1
What am I doing wrong here... I've compared it to one of the other times I'm doing this and it seems to be the exact same. Why isn't it recognizing it's an array?
Thanks,
Matt
Try converting the json data in profile to a proper object by using eval() on it.
Example:
var profileObject = eval('(' + profile + ')');
Hmmm, I'd be doing what you're trying to do a little differently.
I'd either return a fully qualified object and then use it's properties;
class MyObj
{
public string name{get;set;}
}
fill the object and return it as a json object. then you're jquery code can access like any other object.
The other way might be to do a return PartialView("MyView", model);
That will return the partial view as html back to your page which you can then append to your html.
I think the type of profile is string instead of array. Why? Check the $.post method parameters. Maybe the problem is there.
$.post("url", null, function(profile) { ... }, "json");

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

I have a complex JSON object which is sent to the View without any issues (as shown below) but I cannot work out how Serialize this data back to a .NET object when it is passed back to the controller through an AJAX call. Details of the various parts are below.
var ObjectA = {
"Name": 1,
"Starting": new Date(1221644506800),
"Timeline": [
{
"StartTime": new Date(1221644506800),
"GoesFor": 200
}
,
{
"StartTime": new Date(1221644506800),
"GoesFor": 100
}
]
};
I am not sure how this object can be passed to a Controller Method, I have this method below where the Timelines object mirrors the above JS object using Properties.
public JsonResult Save(Timelines person)
The jQuery I am using is:
var encoded = $.toJSON(SessionSchedule);
$.ajax({
url: "/Timeline/Save",
type: "POST",
dataType: 'json',
data: encoded,
contentType: "application/json; charset=utf-8",
beforeSend: function() { $("#saveStatus").html("Saving").show(); },
success: function(result) {
alert(result.Result);
$("#saveStatus").html(result.Result).show();
}
});
I have seen this question which is similar, but not quite the same as I am not using a forms to manipulate the data.
How to pass complex type using json to ASP.NET MVC controller
I have also seen references to using a 'JsonFilter' to manually deserialize the JSON, but was wondering if there is a way to do it nativly though ASP.NET MVC? Or what are the best practices for passing data in this way?
Edit:
This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
You can use this ObjectFilter:
public class ObjectFilter : ActionFilterAttribute {
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
object o =
new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
You can then apply it to your controller methods like so:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.
You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.
$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:
Data to be sent to the server. It is
converted to a query string, if not
already a string. It's appended to the
url for GET-requests. See processData
option to prevent this automatic
processing. Object must be Key/Value
pairs. If value is an Array, jQuery
serializes multiple values with same
key i.e. {foo:["bar1", "bar2"]}
becomes '&foo=bar1&foo=bar2'.
Therefore:
You aren't passing JSON to the server. You're passing JSON to jQuery.
Model binding happens in the same way it happens in any other case.
A different take with a simple jQuery plugin
Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.
This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.
You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.
All you have to do is to use this plugin on the client side. An Ajax request would look like this:
$.ajax({
type: "POST",
url: "SomeURL",
data: $.toDictionary(yourComplexJSONobject),
success: function() { ... },
error: function() { ... }
});
But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.
There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject method that just makes a plain object. You can then use reflection to get at the properties you need.
If your controller takes a FormCollection, and you didn't add anything else to the data the json should be in form[0]:
public ActionResult Save(FormCollection forms) {
string json = forms[0];
// do your thing here.
}
This answer is a follow up to DaRKoN_'s answer that utilized the object filter:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.
What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:
public class SomeViewModel()
{
public Person Person { get; set; }
public Address Address { get; set; }
}
Then I would bind the view to SomeViewModel. You can do the same thing with JSON.
[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
Person p = jsonViewModel.Person;
Address a = jsonViewModel.Address;
// Do stuff
jsonViewModel.Person = p;
jsonViewModel.Address = a;
return Json(jsonViewModel);
}
Then in the view you can use a simple call with JQuery like this:
var json = {
Person: { Name: "John Doe", Sex: "Male", Age: 23 },
Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};
$.ajax({
url: 'home/doJsonStuff',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json), //You'll need to reference json2.js
success: function (response)
{
var person = response.Person;
var address = response.Address;
}
});
in response to Dan's comment above:
I am using this method to implement
the same thing, but for some reason I
am getting an exception on the
ReadObject method: "Expecting element
'root' from namespace ''.. Encountered
'None' with name '', namespace ''."
Any ideas why? – Dan Appleyard Apr 6
'10 at 17:57
I had the same problem (MVC 3 build 3.0.11209.0), and the post below solved it for me. Basically the json serializer is trying to read a stream which is not at the beginning, so repositioning the stream to 0 'fixed' it...
http://nali.org/asp-net-mvc-expecting-element-root-from-namespace-encountered-none-with-name-namespace/

Resources