简体   繁体   中英

MVC 5: Submit button hitting wrong action in controller

I have a form which on clicking on the submit button goes to an action in a controller. This works fine. The action returns a view with a view model:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Title,Name,Surname,Email,ContactNumber")]ClientViewModel clientViewModel)
    {
        *some actions*
        return View("SaveClient", matchesClientViewModel);
    }

The SaveClient.cshtm:

@model BusinessModels.MatchesClientViewModel
@{
    ViewBag.Title = "SaveClient";
}

<h2>SaveClient</h2>

<h3>
bla bla
</h3>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()


    WebGrid grid = new WebGrid(Model.ClientMatches);
    @grid.GetHtml(columns: new[]

                         {
                    grid.Column("Name"),
                    grid.Column("Surname"),
                    grid.Column("Email"),
                })


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>

}

And in my controller I have the following action:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SaveClient(MatchesClientViewModel matchesClientViewModel)
    {
        *some actions*
        return View();
    }

However, the submit button is not hitting the the SaveClient action but the Create action. On inspecting the form in IE, I can see that the form goes to the /Client/Create action.

I have tried replacing

@using (Html.BeginForm()) with but it does not work.

My route config is:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

Any idea what I am doing wrong here? Please help, I am on this since 2 days.

There are some things driven by convention in MVC framework. So what you need is to specify the action and controller name explicitly to post it to your own defined action name that is different than conventional:

@using (Html.BeginForm("SaveClient","ActionName",FormMethod.Post))

You can add onclick="location.href='@Url.Action("Action", "Controller")'" to your input element. In your case "Action" (name of the Action method) would be "SaveClient" and "Controller" (name of the Controller) would be "Client" :

<input type="submit" value="Save" class="btn btn-default" onclick="location.href='@Url.Action("SaveClient", "Client")'" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM