Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 - Can We Use Model Binding Over jQuery AJAX Calls?

If i have the following jQuery function (in an external file):

function getResults(field1, field2, field3) {
   $.get('/Search/GetResults', { id: field1, type: field2, blah: field3 }, function(data) {
      $('#target').html(data);
   });
}

Which essentially takes a bunch of fields from the form, sends them to an action method (which returns a PartialViewResult), and binds the result to a target div.

Here is that action method:

[HttpGet]
public PartialViewResult GetResults(int id, int type, string blah)
{
   var model = repository.GetResults(id, type, blah);
   return PartialView("Results", model);
}

Is it possible to use model-binding here? E.g can we do this:

function getResults(someModel) {
   $.get('/Search/GetResults', { model: someModel }, function(data) {
      $('#target').html(data);
   });
}

And this:

[HttpGet]
public PartialViewResult GetResults(SearchPreferences prefs)
{
   var model = repository.GetResults(prefs);
   return PartialView("Results", model);
}

Or should i construct a JSON object and pass that? Currently those values are retrieved via individual jQuery DOM calls:

var field1 = $('#field1').val();
var field2 = $('#field2').val();

The goal is to reduce/simplify jQuery code. I have all those calls to grab all the values, then i need to pass them all as parameters.

Ideally i'd like to just pass one object.

Any recommendations?

EDIT: Just realized i may be able to use the new JSON Model Binding feature in ASP.NET MVC 3. Reading up on it now... (feel free to answer in advance in the meantime).

like image 806
RPM1984 Avatar asked Jan 21 '11 00:01

RPM1984


People also ask

Can we implement Ajax using jQuery in MVC?

Using AJAX In ASP.NET MVC. Implementation of Ajax can be done in two way in ASP.Net Application: using Update Panel and, using jQuery.

Which JavaScript library is used by ASP.NET MVC to make Ajax calls?

Ajax functionality depends on the jQuery library, but not the Bootstrap library. If the web project does not implement the Bootstrap CSS framework, the Bootstrap library is unnecessary.


1 Answers

In ASP.NET MVC 3, YES! Check out this link, from TheGu himself.

ASP.NET MVC 3 now includes built-in support for posting JSON-based parameters from client-side JavaScript to action methods on the server. This makes it easier to exchange data across the client and server, and build rich JavaScript front-ends.

like image 160
Chaddeus Avatar answered Sep 28 '22 07:09

Chaddeus