我是MVC的新手并且搞乱了。这一直让我疯狂,我一直在阅读,似乎我可能在我的代码结构中有一些基本错误。但我正在努力去看他们究竟是什么。据我所知,我甚至没有使用儿童行动?
返回RedirectToAction行时会抛出错误。
我有一个注册表单,我以模态显示。这个模态可以在许多页面上看到 - 所以我创建了一个返回局部视图的动作。
[AllowAnonymous]
public ActionResult RegisterPartial()
{
return PartialView(new RegisterModel());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult RegisterPartial(RegisterModel model)
{
if (ModelState.IsValid)
{
//do stuff
return RedirectToAction("Data", "Settings", new { id = model.UserName });
}
// If we got this far, something failed, show form again
return PartialView(model);
}
此时从我的主页调用 - 但最终将从多个页面调用。
<div class="modal fade" id="signUpModal">
@Html.Action("RegisterPartial", "Account")
</div>
<a href="#" style="color:#fff;" class=" btn btn-lg btn-primary" data-toggle="modal" data-target="#signUpModal">SignUp</a>
这是局部视图本身
@model Prog.Models.RegisterModel
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Signup</h4>
</div>
@using (Html.BeginForm())
{
<fieldset>
<div class="modal-body">
<p class="message-info">
</p>
@Html.ValidationSummary()
@Html.AntiForgeryToken()
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName, new { @maxlength = "13" })
@Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.email)
@Html.TextBoxFor(m => m.email)
@Html.ValidationMessageFor(m => m.email)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</ol>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Post</button>
</div>
</fieldset>
}
</div></div>
任何帮助都将非常感谢!在此先感谢:)
答案 0 :(得分:1)
原来是因为我没有正确填写html开始表单语句。
@using (Html.BeginForm("RegisterPartial", "Account", FormMethod.Post , new { @class = "form-horizontal" }))
现在可以使用。
答案 1 :(得分:0)
问题是如果modelstate无效,你的POST动作将返回PartialView。因此局部视图将显示为整个页面而不是模型。所以你可以使用ajax表单。有一个Ajax Helper可用于MVC。
在页面中包含以下脚本。
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
您的观点将是
@using (Ajax.BeginForm("RegisterPartial", "Account", new AjaxOptions() {
OnSuccess = "successCallback"})
{
}
<script>
function successCallback(response)
{
var username='@Model.UserName';
if(response)
{
windows.href.location='/Settings/Data/'+username;
}
}
</script>
您的行动将是
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResultRegisterPartial(RegisterModel model)
{
if (ModelState.IsValid)
{
//do stuff
return Json(new {Success=true });
}
return Json(new {Success=false});
}
可能会有所帮助。