0

In my example I'm unable to call a controller from a button click. My button code is :

<button id="confirmsignup" name="confirmsignup" class="btn btn-success" onclick="location.href='@Url.Action("RegisterUser", "Home")'" >Sign Up</button>

My Controller is HomeController.

My Action Method is :

[HttpPost]
    public ActionResult RegisterUser(UserInfo objUser)
    {

        int res= udaObj.RegisterUser(objUser);
    }
2
  • location.href won't post back. It redirects the current page to /Home/RegisterUser page with HttpGet status. What are you trying to achieve? Commented Jun 27, 2017 at 17:53
  • On that button click, I need to hit that RegisterUser method for inserting my data. Commented Jun 27, 2017 at 17:55

2 Answers 2

1

The line location.href="someurl" will issue a new GET request to that url, not a form post!

To submit the form (and it's data) to the HttpPost action method, Wrap your form elements inside a form tag and have the button submit it. Have the action attribute of form set to RegisterUser action method.

You can use the Html.BeginForm helper method to generate the form tag markup.

@using(Html.BeginForm("RegisterUser","Home"))
{
  <!-- your other input form elements goes here -->

  <button id="confirmsignup" type="submit" 
                   name="confirmsignup" class="btn btn-success" >Sign Up</button>

}
Sign up to request clarification or add additional context in comments.

4 Comments

Can I use one more like that(html.beginform...) in my cshtml page ? Because my another div contains another button which should hit LoginUser in the same controller.
Yes. you can have more than one form in the same view. But make sure they are not nested. Nested forms are invalid html
When I used two buttons 1 for login and 1 for registration, the registration is not redirecting whereas login is hitting controller.
I said 2 forms. not two buttons in same form.
0
<button id="confirmsignup" name="confirmsignup" class="btn btn-success" onclick="location.href='@Url.Action("RegisterUser", "Home")'" >Sign Up</button>

the above code defines like has HTTP GET method .so you cann't call the Registeruser method when button click.

So you just use MVC form submit or jquery post to call that HTTP POST method Or else it consider has GET method.

1 Comment

Means, Can I use this method for both buttons with their concern action methods ?

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.