Ali Exalter
Ali Exalter

Reputation: 420

jquery.POST to MVC controller to return JSON

I have created a following model

public class myModel
{
    public int ID;
    public string Name;
    public int[] days;
}

Then I created an action in a controller

[HttpPost]
public ActionResult myCtrlAction(myModel thisModel)
{
   if (ModelState.IsValid)
        {
            return Json(thisModel);
        }
        else
        {
            string errorMessage = "<div class=\"validation-summary-errors\">"
              + "The following errors occurred:<ul>";
            foreach (var key in ModelState.Keys)
            {
                var error = ModelState[key].Errors.FirstOrDefault();
                if (error != null)
                {
                    errorMessage += "<li class=\"field-validation-error\">"
                     + error.ErrorMessage + "</li>";
                }
            }
            errorMessage += "</ul>";
            return Json(new myModel { Name = errorMessage });  //just for now
        } 
   }

In my javascript I send the data using jQuery.post() as

$("#myBtn").click(function () {
var mydata = {
          ID: $("#inputID").val(),
          Name: $("#inputName").val(),
          Days: $("#selectDays").select2("val")
       }
    var url = 'myController/myCtrlAction';  //definitly it was writtern as @Url.Action
    $.post(url, mydata, function(data) { alert(data); //which shows [object object] 
                     }, 'json');
 });

Now On request when I debug in Chrome I saw in headers as

Form Data ID: 5 Name: SomeName Days[]: 6 Days[]: 5

In Response I got json format of my model as

{ID: "0", Name: "null", Days: "null"} it means my model state is valid but why its not having the values?

Any body has any idea. what I did wrong or do I miss something?

Upvotes: 3

Views: 11977

Answers (3)

florian.isopp
florian.isopp

Reputation: 862

I do this following:

  • 1: JavaScript: When clicking the button: Serialize the form-data and send it to the Controller:

    function ajaxSubmitEditSupplierQuote() {
        var formData = $("#SupplierQuoteEditForm").serializeArray();
        $.ajax({
            type: "POST",
            url: '@Url.Action("Edit", "SupplierQuote")',
            data: formData,
            dataType: "json",
            cache: false,
            success: function (data1) {
                // Here I create then a new Url-string.   
                // Simple access your Json Data, as you have named it in the return of the Controller-Action.
                var strUrl = "/Equipment/" + data1.target.toString();                   
                // ...
                // 
                // ...
            }
        });
    }        
    
  • 2: Controller-Action with custom Json return

    [HttpPost]
    public ActionResult Edit(SupplierQuoteDto supplierQuoteDto)
    {
    
        // ........... code
    
        if (_userContext.EquipmentAction.ClickedAction == ActionType.Create)
            return Json(new { target = "Create" });
        else if (_userContext.EquipmentAction.ClickedAction == ActionType.Edit)
            return Json(new { target = "Edit" });
        else
            return new EmptyResult();
    }
    
  • 3: Alternatively if you want to catch also the EmptyResult() then in the JavaScript, check simply in the

    success: function (data1) { 
        if (data1.toString() == "") {
            // .... alert
        }
        else {
            /// .... go on with coding
        }
    }
    

Upvotes: 1

mwangi
mwangi

Reputation: 1626

I think your model's data is not set thus you get null values on Chrome.

If your javascript does not have a typo (and that you only made a typo when creating the question, then try this in your method myCtrlAction;

First try create getters and setters for your fields in myModel. Then;

replace;

 errorMessage += "</ul>";

 return Json(new myModel { Name = errorMessage });  //just for now

with this;

 myModel myMODTest= new myModel();
 myMODTest.setID(1111);
 myMODTest.setName("testName");
 myMODTest.setDays({1,2,3});
 return Json(myMODTest);  //just for now

See if you get on your browser the following;

{ID: "1111", Name: "testName", Days: "{1,2,3}"}

Upvotes: 1

Peter
Peter

Reputation: 14508

check your javascript code where you do the post. You have a typo: '.' instead of ',':

$.post(url, mydata, function(data) { alert(data); }, 'json');

Upvotes: 0

Related Questions