How to send model in ajax type get?

Viewed 41

I am using Asp.net MVC and I would like to send a get request along side with model. I am sure this can be done via post request be in this case I will not get data back.

So my request is:

$.ajax({
                type: "GET",
                url: '@Url.Action("ActionName", "Controller")',
                data: {model: { model1: {id:1,name:"Test1"}, model2: null, model3: null }, serverName: "ServerTest"
                },
                datatype: "json",
                cache: false,
                success: function (data) {
                    $("#table1").html(data);
           },
           error:function (xhr, ajaxOptions, thrownError){
                  alert(xhr.responseText);
                }
            });

Action:

public ActionResult TestSpecSearchResult(MainModel model, string serverName)
{
//Do somethin
 return PartialView(data);
}

Please note MainModel contain model1,model2 and model3.

1 Answers

Assuming that your model class:

public class Model
{
public int Id {get; set;}
public string Name {get; set;}
}

and your MainModel class:

public class MainModel
{
public  Model Model1 {get; set;}
public  Model Model2  {get; set;}
public  Model Model3 {get; set;}
}

you will have to create MainViewModel:

public class MainViewModel
{
public  MainModel Model {get; set;}
public string ServerName {get; set;}
}

Then the action will be :

public ActionResult TestSpecSearchResult([FromBody] MainViewModel model)
{
//Do somethin
 return PartialView(data);
}

And the ajax:

var data = { 
Model: { Model1: {id:1,name:"Test1"}, Model2: {}, Model3: {} }, 
ServerName: "ServerTest"
};    

$.ajax({
       type: "GET",
        url: '/..Controller.. /TestSpecSearchResult',
         data: data,
        success: function (data) {
                    $("#table1").html(data);
           },
          error:function (xhr, ajaxOptions, thrownError){
                  alert(xhr.responseText);
                }
            });

The code was tested in Postman and working properly with GET and POST.

UPDATE:

I just tested this code in Visual Studio 2019 with Net5 and found that using [FromBody] attribute gives null when using Ajax, so remove [FromBody] attribute although without this it will not be testable in Postman. "Get" works in Postman, but doesn't work with Ajax. it shows only ServerName. So you have to use "POST" with Ajax or change your ViewModel by removing all nested classes. You will have to put all the properties in one level. Only in this case GET will be working with request body.

Related