I’ve passed my model in the View to the Controller with the following jQuery Ajax code:
$.ajax({
data: model,
type: "POST",
url: '@Url.Action("createDoc")',
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert('Done '+ result.toString());
}
});
The problem is: in the Controller method “createDoc”
[HttpPost]
public ActionResult createDoc(IEnumerable<Movie> movies)
{
CreateWordprocessingDocument(movies);
return Json(new { result = movies.Count()});
}
I can’t do anything with the movies Enumerable data.
The call to the CreateWordProcessingDocument create a document with the movies data. But it does not.
This is the method code:
public void CreateWordprocessingDocument(IEnumerable<Movie> movies)
{
HttpContextWrapper context = new HttpContextWrapper(System.Web.HttpContext.Current);
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", "attachment;filename=example.doc");
context.Response.ContentType = "application/vnd.ms-word.document";
context.Response.Charset = "";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<p align='Center'><b> GENERAL TITLE</b></p>");
sb.Append("<br>"+movies.Count());
for (int i = 0; i < movies.Count(); i++) {
sb.Append("<br>Title:" + movies.ElementAt(i).Title +"");
}
context.Response.Output.Write(sb.ToString());
context.Response.Flush();
context.Response.End();
}
But it doesn’t work: it returns to the ajax post and pop ups the “Done” alert, with the result.tostring() showing the HTML code I create on the createWordProcessingDocument method.
How can I avoid this behaviour so I can do something with the data I pass to the controller from the View?
Thanks.
Problem solved: I post the solution here, if it can helps someone with my problem.
In my createDoc method I create the string with the wanted data, then I put them in a tempData proprierty. That’s what createDoc looks like:
Then the “control” returns to the Ajax post method, and at the end of it I put this:
So my Ajax post full code is:
Now the “control” is redirect to the CreateWordProcessingDocument action, where I actually create the document:
That’s all. Thank u all for your help, hope that I can help someone with this solution.