Friday, February 24, 2012

Post Form Data using jQuery $.post() or jQuery.post()

Post Form Data using jQuery $.post() or jQuery.post()


// script tag in html page

$("#btnGetDetails").click(function (){

var txtOrderId= $("#txtOrderId").val(); // assuming form1 is the id of the form we are trying to submit
var url= "controllerName/actionName" // set target url

$.post(url,{OrderId:txtOrderId},function(res){
// process Response Data
});

});

//  Controller Action

public ActionResult actionName(int OrderId)
{
// TO do task
return resultstring;
}

Name specified in Red should match otherwise we wont be able to get values on Action method.

But if think same we cam do to post form data then this is not the case where it will work. To post form data
we need some changes in code as specified below:


$("#btnSubmit").click(function (){

var formData= $("#form1").serialize(); // assuming form1 is the id of the form we are trying to submit
var url= "controller/action" // set target url

$.post(url,formData,function(res){
// process Response Data
});

});
//  Controller Action

public ActionResult actionName(OrderModel modelData) // assuming view is strong typed view
{
// TO do task
return resultstring;
}

public ActionResult actionName(FormCollection modelData) // assuming view is not strong typed view
{
// TO do task
return resultstring;
}

in this case we don't need to map parameter in action method and post parameters.

Edit: 3 May 2012

A few days back i was caught in a situation where i had to send some other parameter along with formData so initial i wasnt aware of what should i need to do but with the help of my friend (Rohit Rao)  i got this solution.
so if we have to send additional parameter with formdata

$("#btnSubmit").click(function (){

var formData= $("#form1").serialize(); // assuming form1 is the id of the form we are trying to submit
var url= "controller/action?param1=val1&param2=val2" // set target url Line:1
// url= "controller/action"                        Line:2
$.post(url,formData,function(res){
// process Response Data
});
});

Line 1 with query sting parameter and Line 2 is without parameter we can call same action with following action method definition.

//  Controller Action

public ActionResult actionName(string param1="",string param2="",OrderModel modelData) // assuming view is strong typed view
{
// TO do task
return resultstring;
}
we have assigned default values to param1 and param2 in the case where both are missing from query string parameter.

Note: I am not sure about below action method because it isn't tested  but as much as i know there isn't any reason it shouldn't work.
public ActionResult actionName(string param1="",string param2="",FormCollection modelData) // assuming view is not strong typed view
{
// TO do task
return resultstring;
}



I hope this will help you.

Happy Living...
Happy Concept...
Happy Coding....

No comments:

Post a Comment