开发者

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

开发者 https://www.devze.com 2023-02-06 02:12 出处:网络
If i have the following jQuery function (in an external file): function getResults(field1, field2, field3) {

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 rec开发者_开发知识库ommendations?

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).


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.


If you create a class that contains the properties that you are sending over, the default model binder will kick in and bind the data to that class. In your example, create a class:

public class SearchPreferences 
{
  public int id { get; set; }

  public int type { get; set; }

  public string blah { get; set; }
}

Then in your action it can be:

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

They key is to have the names in your $.get data match the names in your SerachPreferences class.

0

精彩评论

暂无评论...
验证码 换一张
取 消