我有一个页面,其中设置了多个部分。我希望能够分别验证和更新每个部分。验证工作但是当我输入正确的值并按保存时,页面转到部分视图而不是停留在单个页面上。我在这里做错了什么?
这是我的主页:
@for (var i = 0; i < 10; i++)
{
var idTest = "Test_" + i;
<div id="@idTest">
@Html.Action("Detail", new { id = i })
</div>
}
部分创建如下:
@{
var idTest = "Test_" + Model.Id;
var ajaxOptions = new AjaxOptions
{
UpdateTargetId = @idTest,
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace
};}
@using (Ajax.BeginForm("Detail", ajaxOptions))
{ @Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Test</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Gemeente, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Gemeente, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Gemeente, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
这是一个简单的模型:
public class Test
{
public int Id { get; set; }
[Required(ErrorMessage = "Gelieve een gemeente op te geven")]
public string Gemeente { get; set; }
}
这些是行动:
[HttpGet]
public ActionResult Detail(int id)
{
Models.Test model = new Models.Test();
model.Id = id;
return View(model);
}
[HttpPost]
public ActionResult Detail(Models.Test model)
{
if(ModelState.IsValid)
{
return PartialView(model);
}
return PartialView(model);
}
答案 0 :(得分:0)
将这些行添加到您的视图中,并使用@ Html.Partial,如下所示
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
以便您的主视图
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@for (var i = 0; i < 10; i++)
{
var idTest = "Test_" + i;
<div id="@idTest">
@Html.Partial("Detail", new Test { Id = i })}
</div>
}
脚本将用于不显眼的ajax,以便你的ajax按钮工作和Html.Partial,这样第一次在foreach中加载你的页面时,只呈现部分视图(不是完整视图)