我是MVC的新手,我一直在创建提交表单。
Model Email.cs:
using System.Web;
namespace MySite.Models
{
public class Email
{
public string From { get; set; }
public string Subject { get; set; }
public string body { get; set; }
}
}
Controller CommunicationController.cs:
namespace MySite.Controllers
{
public class CommunicationController : Controller
{
public ActionResult SendEmail() {
Email email = new Email();
return View(email);
}
[HttpPost]
public ActionResult SendEmail(Email email)
{
if (ModelState.IsValid)
{
}
return View(email);
}
}
}
查看SendEmail.cshtml:
@model MySite.Models.Email
@{
ViewBag.Title = "SendEmail";
}
<h2>@Html.Label("Send email")</h2>
@using(Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.Label("From")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.From)
</div> <div class="editor-label">
@Html.Label("Subject")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Subject)
</div> <div class="editor-label">
@Html.Label("Body")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.body)
</div>
<input id="btnSubmit" type="submit" value="SendEmail" />
}
当我按提交时,事件永远不会被解雇。在控制器中,如果我按“去”查看&#39;然后它进入SendEmail视图。我不知道发生了什么事。我试图调试,但[HttpPost]控制器永远不会被解雇。
以下是我从浏览器获得的内容,我看不到行动
<form method="post" action="/" novalidate="novalidate">
<input type="hidden" value="ZktM_I7fzdlcNme4YVEcNNpnFFmQu1cpAuTXarO_V4w-7bPmpHkaLRfNY3cXGMYy7wkRgSJWWSkS8lp5vdRimFrNCgqk0Jfdr4v7Zc3V2pg1" name="__RequestVerificationToken">
<div class="editor-label">
<div class="editor-field">
<input id="From" class="text-box single-line" type="text" value="" name="From">
</div>
<div class="editor-label">
<div class="editor-field">
<div class="editor-label">
<div class="editor-field">
<input id="btnSubmit" type="submit" value="SendEmail">
</form>
答案 0 :(得分:0)
试试这个,
@using (Html.BeginForm("ActionName", "ControllerName",
FormMethod.Post))
{
//form UI
<input id="btnSubmit" type="submit" value="SendEmail" />
}
你也可以试试这个:
<a onclick="$('#formId').submit();">Submit</a>
or
<button type="submit">Submit</button>
答案 1 :(得分:0)
我很少使用基本助手,所以我可能错了,但我相信你得到的默认方法
Html.BeginForm()
是GET。所以,你可能想要使用
Html.BeginForm("SendEmail", "Communication", FormMethod.Post, new { /* html attributes */ })
然后,要测试您是否真正击中控制器,请在操作中添加:
ModelState.AddModelError("", "Action was called!");
这将在ValidationSummary中显示为错误,这没关系,因为我们只是在这里进行调试。
答案 2 :(得分:0)
我参加派对有点晚了......
尝试更换:
<input id="btnSubmit" type="submit" value="SendEmail" />
使用:
<button id="btnSubmit" type="submit" name="submitButton value="SendEmail" />
如果有效,或者您找到了其他解决方案,请告诉我们! :)