Razor Input with two actions

219 Views Asked by At

I have a simple submit input :

@using (Html.BeginForm())
{
      <input type="submit" value="Save" id="SaveButton" class="btn" />
}

And now I want to make this button also a hotlink. When I click it, I want to move to "X" Action.

I tried with:

onclick="location.href='@Url.Action("Index", "Student")'"

But it only submits changes, and refresh actual page. Redirect works if input is outside @using(...), but that of course doesn't help me.

1

There are 1 best solutions below

0
On

What I would do is submit your form using JavaScript:

In your form declaration add a onsubmit event handler

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new
{       
    onsubmit = "javascript:onFormSubmit(this); return false;"
}))
{
    <!-- your form -->
} 

Then the onsunmit javascript function submit the form like this:

function onFormSubmit(form)
{
    var data = new FormData($(form)[0]);
    if ($(form).valid())
    {
            $.ajax({
                url:  $(form).attr('action'),
                cache: false,
                processData: false,
                contentType: false,
                data: data,
                type: 'POST',
                error: function(jqXHR, textStatus, errorThrown)
                {
                    throw new Error('Cannot get action');
                }
            }).done(function(view)
            {
                // redirect here....
            });
        }
}

If you don't want to do it this way, in your Index Action rather than returning the View do this:

return Redirect("http://www.google.com");// or any url you want

Another way is to redirect to a different Action like so:

return RedirectToAction("RedirectAction");

Then add another action in your controller called "RedirectAction".

public ActionResult RedirectAction()
{
   // Do some stuff
    return Redirect("http://www.google.com");// or any url you want
}

Hope this helps.