Reputation: 31
I have a div which contains HTML table and i need to pass that table to controller in MVC3 . I am trying to pass the table using ajax call . While debugging i get my controller to my action declared but the value passed HTML table is coming as null. Do i sending it correctly. what is the problem is sending it. Please refer the below link even this they have faced same problem how to send html table from view to controller in mvc4
The below is my ajax call code :
$('#frmLogin').submit(function () {
var sendhtml = $('#divCashResultHolder').html();
//alert(sendhtml);
$.ajax({
url: '@Url.Action("ExportData", "CashCollection")',//action method url which defined in controller
type: 'POST',
data: { "htmlTable": sendhtml },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
success: function(){
console.log('success!!');
}
});
The controller Code
[HttpPost]
public ActionResult ExportData(string htmlTable)
{
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-disposition", "attachment;filename=CashCollection_" + DateTime.Now.Ticks + ".xls");
return View("CashCollection");
}
In the controller i get 'string htmlTable' as null value. I tried setting it to HTMLstring type no luck. Also, i tried sending data: JSON.stringify(sendhtml ) no luck for this too.
Upvotes: 0
Views: 2117
Reputation: 73
The problem here is while data is coming to controller. It is validating. By default they do not allow to send html data to control.
To allow we could use [ValidateInput(false)]
Then your controller should look like this:
[HttpPost]
[ValidateInput(false)]
public ActionResult ExportData(string htmlTable)
{
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-disposition", "attachment;filename=CashCollection_" + DateTime.Now.Ticks + ".xls");
return View("CashCollection");
}
If this is not working. Then its may be your ajax method problem. Then try to send your data as FormData. Then your ajax method should like this:
$('#frmLogin').submit(function () {
var sendhtml = $('#divCashResultHolder').html();
//alert(sendhtml);
var fd = new FormData();
fd.append("htmlTable", sendhtml );
$.ajax({
url: '@Url.Action("ExportData", "CashCollection")',//action method url which defined in controller
type: 'POST',
data: fd,
enctype: 'application/form-data',
processData: false,
contentType: false,
success: function(){
console.log('success!!');
}
});
Upvotes: 0
Reputation: 10694
Try passing the data using JSON.stringify
data: JSON.stringify({"htmlTable": sendhtml});
Upvotes: 3