1
votes

I have a view with the following code:

@using (Html.BeginForm("GenerateQrCode", "QrCodeGenerator", FormMethod.Post ))
{
    <input type="submit" value="Generate" />
}

It's just a submit button, which calls the code in my controller:

    public void GenerateQrCode()
    {

    }

Is it possible for a method in my controller to return a value from the form, but without going to a different page? Because I notice that currently, on pressing the form button it tries to navigate to a non-existing 'GenerateQrCode' page (the same name as the controller method).

UPDATE:

Something I've tried is making the controller method return an ActionResult, and return a 'RedirectToAction', and simply calling the same view. However, I also had code in this method 'ViewBag.Message = "myMessage"; and then in my view I had the code '@ViewBag.Message', so I hoped that the view would update with the ViewBag message property, but it doesn't appear so.

4
Did you end up solving this problem? - Levi Botelho
Yes, I submitted an answer. - Ciaran Gallagher

4 Answers

0
votes

The version of Html.BeginForm you're using tells the submit button to post to the GenerateQrCode action. Perhaps you could try another overload of Html.BeginForm that better suits your purposes?

0
votes

Using javascript: Handle the click event. In the handler, prevent the default action and stop the event propagation. Make and AJAX call to the server with the form data. Get the response and take further actions.

0
votes

So if I have this right, you want to submit an action without actually taking into account the response from the server. Sounds like you need jQuery post:

$.post(url, $("form selector").serialize(), function () {
    // This is where you put a callback function.
});

That is all you need. This will post the data. What you can do is call this from a button click event instead of a form submit button. Or, you can override the submit event on the form and put this as your first line of code:

e.preventDefault();

where e is your event arguments. This will prevent the default action from occurring, which in this case is the submission of the form and the loading of the response.

0
votes

The simplest method of doing this was simply to use the RedirectToAction method, specifying the name of the controller in the parameters. I also used the TempData variable to pass the results (in this case just a string value) back to the view, and into a ViewBag variable.

    public ActionResult QrCodeGenerator()
    {
        ViewBag.Message = TempData["Message"];
        return View();
    }

    public ActionResult GenerateQrCode()
    {
        TempData["Message"] = "myMessage";
        return RedirectToAction("QrCodeGenerator");
    }