将数据从视图传递到控制器(MVC 3)
本文关键字:控制器 MVC 数据 视图 | 更新日期: 2023-09-27 18:26:11
当我试图将字符串从视图传递到控制器时,我的ASP.NET应用程序出现问题。。。
我的控制器(需要的方法)
`public ActionResult Mail(int id) //Display the View "Mail"
{
Customer customer = db.Customers.Find(id);
return View(customer);
}
[HttpPost,ActionName("Mail")] // this Method allow to send a email
public ActionResult MailConfirmed(int id)
{
Customer customer = db.Customers.Find(id);
string message = Request.Form.Get("messageBody");//Here I try to recuperate my messageBody
if(message!=null)
{
System.Diagnostics.Debug.WriteLine(message);
SendMail(customer.Mail, customer.Name, message);
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Veuillez rentrer un message SVP");
}
return View(customer);
}`
查看"邮件"(经理可以在其中输入邮件正文并单击"邮件"发送邮件的页面)
'@using (Html.BeginForm())
{
<fieldset>
<legend>Customer</legend>
<div class="display-label">Pin</div>
<div class="display-field">
@Html.DisplayFor(model => model.Pin)
</div>
<div class="display-label">Name</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
etc...
<div class="display-field">
@Html.TextBox("messageBody",null)//here the value that I try to pass in my controller
</div>
</fieldset>
}
@using (Html.BeginForm())
{
<p>
<input type="submit" value="Mail" />
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</p>
}`
"消息"始终为空。。。你能帮我吗
像这样更改控制器方法:
[HttpPost,ActionName("Mail")] // this Method allow to send a email
public ActionResult MailConfirmed(int id, string messageBody)
{
Customer customer = db.Customers.Find(id);
if(messageBody!=null)
{
System.Diagnostics.Debug.WriteLine(messageBody);
SendMail(customer.Mail, customer.Name, messageBody);
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Veuillez rentrer un message SVP");
}
return View(customer);
}
此外,您正在从"messageBody"字段传递null。将null更改为"message is this",看看它是否有效。