在 MVC 5 应用程序中,我有一个带有按钮的部分 View ,用于提交一些信息。但是,当我按下该按钮时,父表单将被验证,从而显示所有验证错误。我想要的只是只执行部分 View 中经过验证的字段,而不与父表单交互。
代码更新(部分 View ,UploadFile):
<form action="@Url.Action("Upload","File")" method="post" enctype="multipart/form-data">
<label for="photo">Photo:</label>
<input type="file" name="photo" id="photo" />
<input type="submit" value="Upload" />
</form>
代码父表单:
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.CategoriaId, "CategoriaId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CategoriaId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoriaId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Titulo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Titulo, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Titulo, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Descripcion, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Descripcion, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Descripcion, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Precio, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Precio, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Precio, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
@Html.Partial("UploadFile")
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
最佳答案
既然你有 <form>
标记在部分 View 内,然后输入 @Html.Partial("UploadFile")
里面@using (Html.BeginForm())
如下所示的 block
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
....
....
....
@Html.Partial("UploadFile")
}
它将呈现为这样的嵌套形式
<h2>Create</h2>
<form>
....
....
....
<form action="/File/Upload" method="post" enctype="multipart/form-data">
<label for="photo">Photo:</label>
<input type="file" name="photo" id="photo" />
<input type="submit" value="Upload" />
</form>
</form>
这是无效的 html。您需要搬家@Html.Partial("UploadFile")
@using (Html.BeginForm())
之外 block
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
....
....
....
}
@Html.Partial("UploadFile")
关于asp.net-mvc - 当在局部 View 内按下按钮时,父表单将被验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30707447/