问题
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!

What else can I check to track down the issue? Who is redirecting the page to index???
You can see the output HTML here.
回答1:
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.
回答2:
Try specifying the Action
and Controller
in the BeginForm
method:
Html.BeginForm("Save", "YourController", FormMethod.Post)
回答3:
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.
回答4:
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:
- http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/
and also see this:
- ValidateAntiForgeryToken purpose, explanation and example
回答5:
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.
来源:https://stackoverflow.com/questions/16193615/asp-net-mvc-form-submits-to-index-instead-to-submitting-to-the-right-action