我在部分视图中有这个AjaxForm:
@using (Ajax.BeginForm("CreateStarter", "Player", new AjaxOptions { HttpMethod = "POST"}))
{
@Html.HiddenFor(m => m.OwnerID)
@Html.HiddenFor(m => m.Species)
@Html.HiddenFor(m => m.Gender)
@Html.ValidationSummary(true)
<div class="editor-label">@Html.LabelFor(m => m.Nickname)</div>
<div class="editor-field">
@Html.EditorFor(m => m.Nickname)
@Html.ValidationMessageFor(m => m.Nickname,"", new { @class = "text-danger" })
</div>
<input type="submit" value="Choose my pokemon">
}
在我的控制器发布操作中,我验证模型是否有效。如果不是我返回局部视图。如果模型无效,则返回部分视图,但不显示验证消息。我错过了什么吗? 这是我的行动:
[HttpPost]
public ActionResult CreateStarter(PokemonViewModel pokemonViewModel)
{
if (ModelState.IsValid)
{
Pokemon pokemonEntity = PokemonMapper.GetPokemonEntity(pokemonViewModel);
_userService.AddStarterPokemonToPlayer(pokemonViewModel.OwnerID, pokemonEntity);
return RedirectToAction("PlayerProfile");
}
else
{
return PartialView("_CreateStarter", pokemonViewModel);
}
}
这是我的模特:
public class PokemonViewModel
{
public int ID { get; set; }
public int Species { get; set; }
public string Gender { get; set; }
[Required]
public string Nickname { get; set; }
public int OwnerID { get; set; }
}
答案 0 :(得分:0)
处理部分视图和ajax并不是直截了当的,但也不难。你需要做一些事情:
<div>
)
部分观点。Ajax.BeginForm
中,指定要执行的操作:
HTTP 200 OK
状态,指示请求成功。您需要告知客户某些事情是不对的。第1步和第2步
想象一下,你有一个主页面,你需要为你的部分创建一个容器,并将你的部分放在那里。另请注意OnXxx
函数处理程序。
<html>
<!-- Your main page -->
<div id="your-partial-form-id-here>
@using (Ajax.BeginForm( /* other arguments */
new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "DoBeforeUpdatingPage",
OnFailure = "DoWhenThereIsAnIssue",
OnSuccess = "DoOnSuccess",
UpdateTargetId = "id-of-html-element-to-update-on-success",
}))
{
//...code
}
</div>
</html>
所有OnXxx
处理程序都是javascript方法名称,它们将处理每个方案。以下是您可以在每个方面做的事情:
<script type="text/javascript">
function DoBeforeUpdatingPage() {
// Maybe nothing or maybe form validation
}
function DoWhenThereIsAnIssue(responseFromServer) {
// In your case the responseFromServer is the partial view
// so you just need to inject the html into the container
// you have created earlier.
$('your-partial-form-id-here').html(responseFromServer);
// Also since there was an issue, you may want to clear
// the thing which is updated when it is success
$('#id-of-html-element-to-update-on-success').empty();
}
function DoOnSuccess(responseFromServer) { // whatever... }
</script>
第3步
将BadRequest
返回给客户端,以便调用javascript OnFailure
处理程序;在我们的例子中,将调用DoWhenThereIsAnIssue
。
public ActionResult SomeAction(SomeModel model)
{
if (!ModelState.IsValid)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return PartialView("_NameOfPartial", model);
}
}