问题
ok, after long investigation , it seems like when I have a view that was created to work with the _layout.cshtml - the submit button in the form I have doesn't work (no action is returned to controller).
Only when I created a view and unchecked "Use a layout or master page" - the button has worked!
This seems extremely unclear, so - how can I have both view with the general _layout.cshtml alongside with a working form button?
below: Try to implement a form in MVC4 (+Razor)
Controller (that should get the post action):
public class GeneralController {
[HttpPost]
public ActionResult SearchResults(SearchParamsModel searchParams)
{
// doin some stuff here
return View("SearchResultsView");
}
}
View (.cshtml)
@model Models.SearchParamsModel
@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
{
<section class="form-field">
<input type="text" name="Property1" id="Property1" class="field field139 autocomplete-init-no-img" />
<label for="Property1">value1</label>
<form action="" method="post" class="clearfix">
<input
type="submit"
value="some value"
class="submit btn blue-btn special-submit" />
</form>
</section>
}
Model
public class SearchParamsModel
{
public string Property1{ get; set; }
}
回答1:
You should remove your inner form tag,
@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
will generate a form tag for you.
Also, you should use the html helpers to generate your form elements:
@Html.LabelFor(model => model.Property1)
@Html.TextBoxFor(model => model.Property1)
Could be a possible model binding issue due to this. The submit button belongs to your nested inner form, there is no model that is being submitted here.
@model MvcApplication2.Models.SearchParamsModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
<section class="form-field">
@Html.LabelFor(model => model.Property1)
@Html.TextBoxFor(model => model.Property1)
<input type="submit" value="some value" class="submit btn blue-btn special-submit" />
</section>
}
回答2:
I had similar problem, but not the same problem you described above, resolved this way:
My "MVC 4 Layout Page" had "form" tag inside layout document. On the other side my View was connected to layout page (View page also had "using (Html.BeginForm()){...}")
So, removing "form" tag from layout page should do the thing, "because using (Html.BeginForm()){...}")" from view page is not nested any more.
回答3:
You declare the submit button in a nested Form and the input Property1 is not a descendant of that form. Move the input element into the nested form or remove the nested form altogether
Edit: your nested form element also doesn't specify the action, so if General/SearchResults is not the default for this view, you won't get your expected results
来源:https://stackoverflow.com/questions/19257350/mvc-4-form-submit-button-not-working-when-view-is-using-master-layout