I am making my MVC application. How do I create a button in my view that a click on it will run a function from controller. I would also like to pass data from the view that the button is in. But I do not want to open a different view. I just want to run a function - Button "save to file" would save the table from the view into a file - would open a Directory browser and save a file on a disk.
-
What code have you tried so far? A normal ajax or form submit to a ActionResult which returns JSON data or a ParticalView should work like shown here or hereTot Zam– Tot Zam2017-01-15 20:24:48 +00:00Commented Jan 15, 2017 at 20:24
-
You need to make an effort to put together some code to get better responses. Take a look at Html.ActionLink. Or you can simply have <A href="../ControllerName/MethodName" in the View and in MethodName method in controller, return a file as a response.Allen King– Allen King2017-01-15 20:28:34 +00:00Commented Jan 15, 2017 at 20:28
-
I'm agree with the other friends. More explaining needed! Also check out for Html.RenderPartial too.Serhat MERCAN– Serhat MERCAN2017-01-15 20:41:54 +00:00Commented Jan 15, 2017 at 20:41
Add a comment
|
2 Answers
This will be done with the help of ajax request from your view. You need to add a simple button on your view and call a jquery function on its onclick event like this:
<input type="button" value="save to file" onclick="saveToFile()" />
Then you can create saveToFile function to send ajax request like this: here you can create your data as per your need of fields you want to post to controller. I just adding firstField and secondField for demo:
<script type="text/javascript">
var data = { "firstField" : "value1", "secondField": "value2" };
function saveToFile() {
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
},
error: function (xhr) {
console.log(xhr);
}
});
});
</script>
Your action method will be like this:
[HttpPost]
public ActionResult UseShippingAddress(string firstField, string secondField)
{
//write your logic here to save the file on a disc
return Json("1");
}