3

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?

3 Answers 3

1

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}"}

Sign up to request clarification or add additional context in comments.

5 Comments

let me see, yep I missed get set Awwww come on. How it can be. Thanks mwangi.
Thanks. lolz at my self. It should not be the question but you got the vote. Cheers!
Hi, can you tell me why I have not receive array in my model even I put getter setter for array int[] Days. In Chrome Developer tools arrays are display as Days[]: 6 and Days[]: 5. In response I have Days from my model as NULL. I changed it to List<int> Days in my model it still returning null in Response.
Can you share a screenshot of how it shows on Chrome Developer tools when you have int[] for days?
I got it I have to write, traditional: true in jquery ajax. Thanks. Cheers
1

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
        }
    }
    

Comments

0

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

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

1 Comment

Thanks. Typo fixed, but my concern is why I cannot see in Developer tools (Chrome), the values I sent to the CtrlAction of myController when json retuned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.