Bala
Bala

Reputation: 1139

Pass an object while submitting a form in Javascript

I have something like this in my Controller.

public ActionResult GetResult(Employee employee){
    return RedirectToAction("Index","Employee");
}

I cannot use an Ajax Call because it will do a post and wait for a response, not a submit.

When I have something like this, it works.

[HttpPost]
public ActionResult GetResult(string firstName,string lastName){
  return RedirectToAction("Index","Employee");
}


In javascript 


   var form = $("#Employee);
   form.attr('action','Employee/Index?firstName='Tim'&lastName='Tom');
   form.submit();

The above works when passing parameters as querystring.But I don't know how to pass an object while doing post. I tried using $.post. But it did not work.

Thanks.

Upvotes: 0

Views: 844

Answers (1)

Surya Deepak
Surya Deepak

Reputation: 431

Jquery POST in MVC works this way:

Since your controller action method is:

public ActionResult GetResult(Employee employee)
{
    return RedirectToAction("Index","Employee");
}

You might want your modify your Jquery POST call this way

 var postData=function()
    {

        //prepare javascript object
                var employee=
                {
                  firstName:"firstname",
                  lastName:"lastname"
                };
        $.post('/GetResult',employee,function(data){
        //process the data here using the the data present in data obj
        });
     }

Model binder in mvc checks for the same paramters in the javascript object with the model which you have & and it should also match the parameter name of the action method to the javascript object name.

Let me know if this works out for you.

Thanks

Upvotes: 1

Related Questions