将数据从View传递到Controller(MVC 3)

时间:2012-03-01 15:16:30

标签: c# asp.net-mvc-3

当我尝试将字符串从视图传递到控制器时,我的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>
  }`    

“消息”始终为空...你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

更改您的控制器方法:

[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);
    }

你也是从&#34; messageBody&#34;传递null。领域。将null更改为&#34; message is this&#34;看看它是否有效。