0

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.

3
  • 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 here Commented 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. Commented Jan 15, 2017 at 20:28
  • I'm agree with the other friends. More explaining needed! Also check out for Html.RenderPartial too. Commented Jan 15, 2017 at 20:41

2 Answers 2

1

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");
}
Sign up to request clarification or add additional context in comments.

Comments

1

Apparently, the correct solution was to use

@Html.ActionLink("weekly - PDF", "GenerateTable", "Account", new { group_id = Model.group_id, class_id = Model.class_id, type = 1 }, null)  

And in GenerateTable method just return a proper file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.