ASP.NET MVC form submits to index instead to submi

2019-07-30 06:11发布

I crated a form that is to be used as a partial view.

I placed a breakpoint at the 'Save' action, and when I click the submit button, it validates the data, but never reaches the action, instead the Index action is reached several times!

Here is the code:

@model Models.Category

@using (Html.BeginForm("Save", "Categories", FormMethod.Post))
{
  @Html.AntiForgeryToken()

  <fieldset>
    <legend>Category</legend>

    @Html.HiddenFor(model => model.CategoryId)

    <p>@((Model.CategoryId > 0 ? "Edit" : "New") + " category")</p>

    <div class="editor-label">
      @Html.LabelFor(model => Model.Title)
    </div>
    <div class="editor-field">
      @Html.EditorFor(model => Model.Title)
      @Html.ValidationMessageFor(model => Model.Title)
    </div>

    <div class="editor-label">
      @Html.LabelFor(model => Model.Description)
    </div>
    <div class="editor-field">
      @Html.EditorFor(model => Model.Description)
      @Html.ValidationMessageFor(model => Model.Description)
    </div>

    <p>
      <input type="submit" value="Save">
      @Html.ValidationSummary(true)
    </p>
  </fieldset>
}

Action:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Category category)
{
  throw new Exception("Exception has been thrown!");
}

Here is a screenshot of what happens when I hit 'Save', validation error shows up, but the Save action is not called, nor is the exception ever thrown.
Instead, the Index action is triggered!

enter image description here

What else can I check to track down the issue? Who is redirecting the page to index???

You can see the output HTML here.

5条回答
【Aperson】
2楼-- · 2019-07-30 06:13

The error can also occur if the [Authorize] tag is at the top of the controller. If the user is not logged in, actions not marked with [AllowAnonymous] will not load.

查看更多
何必那么认真
3楼-- · 2019-07-30 06:20

I think this is due to ValidateAntiForgeryToken may be your action method is not map with your form request remove this tag or do this according to giving in this tutorial:

and also see this:

查看更多
时光不老,我们不散
4楼-- · 2019-07-30 06:32

Try specifying the Action and Controller in the BeginForm method:

Html.BeginForm("Save", "YourController", FormMethod.Post) 
查看更多
一夜七次
5楼-- · 2019-07-30 06:35

Are you using unobtrusive validation? If so, the validation is happening client side, assuming that your model specifies Title is requires, which according to your code looks likely.

If you want your action to be called regardless of the validation state, you will need to do your validation in your action, rather than through unobtrusive client side validation.

查看更多
男人必须洒脱
6楼-- · 2019-07-30 06:38

I found the problem in the RouteConfig.cs file.

There was a wrong mapping that confused the routing and I guess it used the Index action as a default instead of the specific action that wasn't found due to the wrong setting.

查看更多
登录 后发表回答