【发布时间】:2014-11-13 18:23:09
【问题描述】:
所以我的局部视图看起来像 -
@model Example.Models.ForgotPasswordViewModel
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
<div style="font-size: 16px; text-align:center; margin-top:10px;">
@Html.ActionLink("Email Link", "ForgotPassword", "Account")
</div>
作为 asp.net 的开箱即用 ForgotPassword 视图的一部分,但我将它变成了部分视图。原来的视图被包裹在“Html.BeginForm(..”中,但我显然不能这样做。(它导致表单中的表单)
如何通过传递声明的 @model 来调用 Account 控制器的 ForgotPassword 方法?
由@Html.TextBoxFor(m => m.Email, new { @class= "form-control" }) 生成的HTML:
<input class="form-control" id="Email" name="Email" type="text" value="" />
您的 AccountController.ForgetPassword(..) 的签名:
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action(
"ResetPassword", "Account",
new { userId = user.Id, code = code },
protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return RedirectToAction("Index", "Home");
}
正如 Erik 指出的,需要确保字段在局部视图中是唯一标识的。该帖子有两次电子邮件。
【问题讨论】:
-
您只能
POST使用表单或ajax 到控制器(IE ActionLink 不提交表单,它只是创建一个超链接)。因此,您的选择是将这个部分移到表单之外,或者使用 javascript/ajax 更改表单目的地,然后提交表单(但要小心,因为现在您在同一个表单上还有可能相互冲突的其他表单元素)。 -
@ErikPhilips 如何使用 AJAX 更改表单的目的地?
-
抱歉打错了,应该是
or use javascript/jquery to change...。 -
Ok.. @ErikPhilips 如何使用 jQuery 更改表单的目的地? :)
-
您不能使用 ajax 来更改表单目的地,但您可以使用 ajax 手动将表单的值发布到任何 actionResult 或 API。然而,这不会很优雅。
标签: c# asp.net-mvc razor asp.net-mvc-5