Fullbalanced
Fullbalanced

Reputation: 87

ASP.NET MVC - AJAX how to correct use?

I just started working with ASP.NET after PHP and have a question regarding using AJAX.

What is the correct methodology?

  1. I googled that have Ajax helpers
  2. Or use jquery code for calling methods from controller
  3. Is it ok to return "ready" html code from controllers to view via ajax request?

For example, Now i use the same

$.post('/ControllerName/ActionFromController', { /* some params */ }, function(data){
     $("#content_div").html(data);
});

my controller

public ActionResult ActionFromController()
{
     // receiving parameters from AJAX request - Request.Form["parameter name"]) 
     // to do something here  

     string cont = "some result of methjd works - HTML table or something else"
     return cont;
}

So is it here any development methodology for using AJAX in asp.net MVC? Or is it ok to use ajax as it described above?

Upvotes: 0

Views: 32

Answers (2)

Dawid Rutkowski
Dawid Rutkowski

Reputation: 2756

I would suggest you to get some more information and possible results types:

Upvotes: 1

Andrei
Andrei

Reputation: 56726

Almost there. The best way to bind your parameters is to strongly type them, which you can do with models. Create a model class:

public class SampleModel
{
    public string ParamName1 {get;set;}
    public int ParamName2 {get;set;}
}

Make sure your actions accepts this as an input:

public ActionResult ActionFromController(SampleModel model)

And when you send your ajax request specify parameters:

$.post(
    '/ControllerName/ActionFromController',
    { "ParamName1": "value", "ParamName2": 1 },
    function(data){
        $("#content_div").html(data);
     }
);

Otherwise what you have look fine.

Upvotes: 1

Related Questions