我只是问自己是否有可能从HttpGet Actionmethod获取值并将它们传递给HttpPost Action方法。
以下是代码:
public class ContactAdminController : Controller
{
[HttpGet]
public ActionResult SendMail()
{
return View();
}
[HttpPost]
public ActionResult SendMail(ContactAdminViewModel contactAdmin)
{
if (ModelState.IsValid)
{
if (DQL.CheckUsernameAndEmail(contactAdmin.username, contactAdmin.email))
{
Mail.SendMail.SendForgotPassword(contactAdmin.username, contactAdmin.email, contactAdmin.message);
return RedirectToAction("LogIn", "Account");
}
}
else
{
ModelState.AddModelError("", "Your username is not associated with the email adress");
return RedirectToAction("LogIn", "Account");
}
return RedirectToAction("LogIn", "Account");
}
}
@model MvcApplication1.ViewModels.ContactAdminViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>SendMail</title>
</head>
<body>
<div>
<p>
@Html.LabelFor(m => m.username, "username")
@Html.EditorFor(m => m.username)
@Html.ValidationMessageFor(m => m.username)
</p>
<p>
@Html.LabelFor(m => m.email, "email")
@Html.EditorFor(m => m.email)
@Html.ValidationMessageFor(m => m.email)
</p>
<p>
@Html.LabelFor(m => m.message, "Your message")
<p>
@Html.TextAreaFor(m => m.message, new { cols = "35", rows = "10", @style = "resize:none" })
@Html.ValidationMessageFor(m => m.message)
</p>
</p>
<p>
@Html.ActionLink("Send", "SendMail", "ContactAdmin")
</p>
</div>
</body>
</html>
public class ContactAdminViewModel
{
[Required(ErrorMessage = "You need to fill in a username")]
public string username { get; set; }
[Required(ErrorMessage = "You need to fill in an email adress")]
public string email { get; set; }
[Required(ErrorMessage = "You need to fill a message for the admin")]
public string message { get; set; }
}
我的问题是我真的不知道如何将值从EditorFors和TextAreaFor传递给HttpPost SendMail方法。我没有在stackoverflow上找到任何合适的东西,也没有从asp.net主页找到任何解决方案。我希望有人可以帮助我:) 提前致谢
答案 0 :(得分:1)
您没有创建要提交给控制器的表单,不是吗?您可以使用BeginForm FormExtension
这样的
@using (Html.BeginForm("SendMail", "ContactAdmin", FormMethod.Post))
{
//Your form here with submit button
}
<form>
标记写入响应。当用户提交表单时,请求将由操作方法处理。using
块中使用此方法。在这种情况下,该方法会在使用块的末尾呈现结束</form>
标记。FormMethod
:处理表单的HTTP
方法,GET
或POST
。因此,如果您想POST
到控制器,SendMail.cshtml
将成为
@using (Html.BeginForm("SendMail", "ContactAdmin", FormMethod.Post))
{
<div>
<p>
@Html.LabelFor(m => m.username, "username")
@Html.EditorFor(m => m.username)
@Html.ValidationMessageFor(m => m.username)
</p>
<p>
@Html.LabelFor(m => m.email, "email")
@Html.EditorFor(m => m.email)
@Html.ValidationMessageFor(m => m.email)
</p>
<p>
@Html.LabelFor(m => m.message, "Your message")
<p>
@Html.TextAreaFor(m => m.message, new { cols = "35", rows = "10", @style = "resize:none" })
@Html.ValidationMessageFor(m => m.message)
</p>
</p>
<p>
<input type="submit" class="button" value="Send" />
</p>
</div>
}