Passing unstructured JSON between jQuery and MVC Controller Actions - c#

There is quite a lot of helpful information on MVC model binding.
My problem stems from the fact that I am trying to avoid creating strongly typed data in my MVC application as it mostly needs to act as a data router.
Basically, I have a set of fields on a page, with a class 'input', that I can gather with jQuery('.input'), iterate over and stuff into a javascript object. I then send this to my ASP.NET MVC controller:
var inputData = my_serialize( $('input');
$.ajax({
type:'POST',
url: '/acme/Ajax/CaptureInput',
dataType: "json",
data: { inputData: JSON.stringify(inputData) },
success: Page_Response_RegisterAndDeposit,
error: Page_AjaxError
});
On the C# side, I have
public JsonResult CaptureInput(string inputDataAsJsonString)
{
JavaScriptSerializer JSON = new JavaScriptSerializer();
object inputData = JSON.DeserializeObject(inputDataAsJsonString);
This seems like a wasteful level of indirection, I'd prefer to pass the data as contentType:application/json and have CaptureInput accept an object or IDictionary or even a dynamic.

You could use the serializeArray method. Let's suppose that you have a form containing the input elements which could be of any type and you want to invoke the following controller action:
public ActionResult CaptureInput(Dictionary<string, string> values)
{
...
}
here's how you could proceed:
<script type="text/javascript">
var values = $('form').serializeArray();
var data = {};
$.each(values, function (index, value) {
data['[' + index + '].key'] = value.name;
data['[' + index + '].value'] = value.value;
});
$.ajax({
url: '#Url.Action("CaptureInput")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
alert('success');
}
});
</script>

Not exactly what you're after but maybe the resolution of this issue would give you a partial workaround, by allowing you to bind to a simple wrapper object with an embedded Dictionary. It might even allow binding direct to a Dictionary. Not sure...
You might also need to explicitly set the json ContentType header in your $.ajax call
"JSON model binding for IDictionary<> in ASP.NET MVC/WebAPI"

Related

Asp.net MVC: controller with first parameter as json and second parameter as string from View

We have a situation where we would like controller to get First parameter as json (model) as second parameter as some additional data other than model (such as Flag, source control from where event is driven etc.), we have tried tweaking with jQuery but all ended up error shown in the browser inspect element.
We have our controller typically like this:
public async Task<ActionResult> Foo(Bar b, string additionaldata)
{
if (additionaldata="Deleted")
{
}
else if (additionaldata="Favorite")
{
}
}
And inside view its something like this:
$("#delete").click(function () {
$.ajax({
url: "/Index/Foo",
type: "POST",
data: $("#myform").serialize(),
dataType: "json"
}).done(function (model) {
$("#Foo_Id").val(model.Foo.Id);
});
});
As far as model is concerned, this jQuery is working fine, but as far as we try to add some additional parameter, we are clueless.
Please suggest how we may pass it.
On option is to use FormData to build the model and add additional data
var formdata = new FormData($('#myform').get(0)); // serialize the form
formdata.append('additionaldata', 'Favorite'); // add additional properties
$.ajax({
url: '#Url.Action("Index", "Foo")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});

Posting form data through Ajax is resulting in Null model data

I'm trying to post my form data which is model bound to a controller via an Ajax request however, the controller is showing that the data is null, despite the request header showing the data is being sent.
Code is below. I've tried data: JSON.stringify(form) which results in a null model whereas the below results in a model with null data.
View
$(document).on('click', '#saveData', function () {
if ($('#form').valid()) {
var form = $('#form').serialize();
$.ajax(
{
url: '#Url.Action("CreateClient", "Processors")',
type: 'POST',
cache: false,
async: false,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(form)
})
.success(function (response)
{ alert(response); })
.error(function (response)
{ alert(response); });
}
});
Controller
public ActionResult CreateClient(ModelData form)
{
if (form == null || !ModelState.IsValid)
{
return Json("Error");
}
return Json("Success");
}
There are two problems with your approach.
If your model class ModelData is, for example,
class ModelData {
public string Foo {get;set;}
public string Bar {get;set;}
}
the appropriate data to send is {foo:"foo1", bar:"bar1"}, or eventually {Foo:"foo1", Bar: "bar1"}, depending on how you have configured your serialization - as you have specified contentType 'application/json'.
However, you are reading your form using jquery serialize(). This method returns a string, on the form "foo=foo1&bar=bar1", appropriate for contentType 'application/x-www-form-urlencoded'. So you have to make up your mind on in what format you want to send the data. If you want to continue to use serialize() to obtain the data from the DOM, use 'application/x-www-form-urlencoded' instead.
Secondly, JSON.stringify() will create a JSON string from an object. A string is an object, too. So passing a string to this function will wrap the string in a string, which doesn't make much sense: The data will be something like "\"foo=foo1&bar=bar1\"". In the same manner, the jQuery ajax function will expect an object for it's data parameter when contentType is 'json', so if you convert your object to a string before, it will be sent just as that: a string. Basically, whatever contentType you end up choosing for your request, don't use JSON.stringify for your data parameter.
TL;DR: To get this working, use the default contentType or declare it explicitly as per below, and pass the form variable as-is:
var form = $('#form').serialize();
$.ajax(
{
//(...)
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: form,
//(...)

MVC Send list through AJAX

Okay, I've seen tons of questions posted regarding this question, but none of the answers has actually worked for me, here's my AJAX:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data: jsonFilters,
traditional: true,
success: function (response) {
//Haha, it's never entering here. not really.
}
});
var "jsonFilters" contains an array with the following data:
[0] = { Path: "Test", Name: "More testing", Value: "Test Value" },
[1] = { Path: "Test", Name: "More testing", Value: "Test Value" }
And this is my controller:
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
jsonFilters always remains null... I have also tried adding contentType: "application/json; charset=utf-8" to the AJAX call... but that didn't really do anything
Finally, the class FilterSessionModel is structured as follows:
public class FilterSessionModel
{
public string Path { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Any ideas as to what I might be missing or what might be happening?
Things I've tried so far:
Setting "traditional: true", setting "contentType", using JSON.stringify and attempting to accept a string in the MVC Controller (no-go)
UPDATE: Thanks to the answer below I realized that what was missing was to send over the data with the param Id like so:
data: "{param1ID:"+ param1Val+"}"
I would try switching out the type on your action.
List<FilterSessionModel>
Pretty sure the above is not going to work, I would try something like Object.
Or possibly a string that I would then use newton json dll to push into your List of Class.
The problem boils down to your action being unable to figure out the type, assuming you are checking your data prior to the ajax get being called.
**Update due to more info. Add in the error portion and view those vars on return from your controller, also fire up fiddler and watch what your are getting for http numbers.
$.ajax({
type: "POST",
url: "Servicename.asmx/DoSomeCalculation",
data: "{param1ID:"+ param1Val+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
UseReturnedData(msg.d);
},
error: function(x, t, m, b) {
//Look at the vars above to see what is in them.
}
});
I think what you are looking for is answered here:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
First off I'm making the assumption that your $.ajax is for JQuery and not some other Javascript framework. Please correct me if that's wrong.
ASP.NET MVC can actually do what you are asking it to (resolve data sent via AJAX to a List<FilterSessionModel>, but it seems to have a difficult time doing it via a GET request. It would help to know which version of ASP.NET MVC you are using, as more is required to get this working on the older versions. However, what I'm suggesting should work on MVC 3 or 4.
When you send AJAX via JQuery using a GET request and passing it a JavaScript array, this is what you are sending to the server:
http://localhost:50195/FilterSessions/GetFilterSession?undefined=&undefined=
It's no wonder the model is null because no data is actually being sent.
I believe ASP.NET can accept objects (and even arrays of objects) like this, but it won't do so with it formatted as JSON (like via JSON.stringify) as that just results in the following request:
http://localhost:50195/FilterSessions/GetFilterSession?[{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22},{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22}]
The way you probably want to do this is with a POST request. ASP.NET MVC will actually accept a JSON string as POST data and will decode it and resolve the model properly. Your AJAX code works fine with a couple modifications:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "POST", //Changed to POST
dataType: "json",
data: JSON.stringify(jsonFilters), //Pack data in a JSON package.
contentType: "application/json; charset=utf-8", //Added so ASP recognized JSON
traditional: true,
success: function (response) {
alert('Success!');
}
});
The controller you posted should recognize POST data already, but in case it doesn't, a simple [HttpPost] attribute is all you need:
[HttpPost]
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
javascript or ajax call never type cast the object. . .you need to set type of the controller side parameter either string or List else you can also set the Object type. . If you modified codein that way.. .Your code definitely work !!!
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data:JSON.stringify({ 'jsonFilters': jsonFilters}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//Do your action
}
});

display json data from controller inside view

Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).

Pass HashTable to View from Controller in MVC 3

Is there a way to pass a HashTable loaded with key/values to a page View in a way I can then use it via javascript/Jquery ?
Example: I have HashTable with
key = Car Model (206 XT), Value = "PEUGEOT", etc...............
So in the view I have a combo with all car models and near that, I have a textbox automatically populated with the manufacturer taken from javascript
Is there a way to do so ??
(I'm really noob in MVC 3 :()
There are different way to solve this problem:
if you wan't to get this list dynamicaly with out reloading you can use a json request (examples).
Javascript:
$.ajax({
type: "POST",
url: "/controler/action",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (result){
for(var i=0; i<result.length; i++) {
var value = result[i];
alert(i =") "+value);
}
}
Controler (c#):
[HttpPost]
public JsonResult Action()
{
return Json(YourTable.ToArray());
}
Furthermore you can access every html-element from javascript. So you can put the content in all kinds of html-elements.
You can serialize most C# objects using the following method in the view:
<script type="text/javascript">
var hashtable = #Html.Raw(Json.Encode(Model.YourHashtable)
</script>
If you have some Tree like data structures with parent/child relationships you might run into issues as the Encoder can't solve circular relationships.

Categories