I'm new to MVC, and currently I'm trying to create a function for my form that exports it values to PDF. I managed to do that using input with submit type that calls the controller. My problem is when I want to keep the values in the form (because I want to create another button that will send the form as e-mail), but the form resets after clicking on the button. I tried creating void function instead of action result, but after calling, the browser tries to redirect to another page with controller names as URL. I also tried to change the input type from submit to button, but after changing it, it won't call the controller on click. So there is my question, how to call the controller without causing the form to reset its values.
Here is index.cshtml that calls the controller
<div >
<div >
<input id="pdfBtn" value="Export to pdf" type="submit" formaction="@Url.Action("pdfExport")" />
</div>
</div>
Here is the controller
[HttpPost]
public ActionResult pdfExport([Bind(Include = "formId,formType,additionalTypeInfo,nameSurname,description,Attachment")] FormModel model)
{
if (ModelState.IsValid)
{
var pdf = new FormToPdf(model);
}
return RedirectToAction("Index");
}
CodePudding user response:
You are doing Redirection in your server side code.
Do an AJAX call to your MVC controller (better if it is Web API controller) and from controller return HTTP OK / HTTP Accepted. While doing AJAX call using JavaScript/jQuery on button click, prevent the default behaviour (submit the form) of the button like in this way:
function onButtonClickPdfExportToServerUsingAjax(e){
e.PreventDefault();
// AJAX call
}
After receiving successful AJAX call response, proceed with whatever you want to do next.
CodePudding user response:
You can try to return the model to Index action like this:
[HttpPost]
public ActionResult pdfExport([Bind(Include = "formId,formType,additionalTypeInfo,nameSurname,description,Attachment")] FormModel [HttpPost]
public ActionResult pdfExport([Bind(Include = "formId,formType,additionalTypeInfo,nameSurname,description,Attachment")] FormModel model)
{
if (ModelState.IsValid)
{
var pdf = new FormToPdf(model);
}
return RedirectToAction("Index");
})
{
if (ModelState.IsValid)
{
var pdf = new FormToPdf(model);
}
return RedirectToAction("Index",model);
}
Or you can use ajax to pass data when button click,so that the page will not be refreshed:
<input id="pdfBtn" value="Export to pdf" type="button" onclick="pdfExport()"/>
js:
function pdfExport() {
$.ajax({
type: "POST",
url: "pdfExport",
data: Data,
success: function (data) {
}
});
}