简体   繁体   English

将数据从View传递到控制器(MVC 3)

[英]Passing data from View to Controller (MVC 3)

I've a problem with my ASP.NET application when I try to pass a string from a view to a controller... 当我尝试将字符串从视图传递到控制器时,我的ASP.NET应用程序出现问题...

My controller (needed method) 我的控制器(所需方法)

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

View "Mail" (Page where the manager can enter a message body and click on "mail" to send the message) 查看“邮件” (经理可以在其中输入邮件正文并单击“邮件”以发送邮件的页面)

'@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>
  }`    

the "message" is always null...Can you help me, please ? “消息”始终为空...请您能帮我吗?

Change your controller method like this: 像这样更改您的控制器方法:

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

Also you are passing null from "messageBody" field. 另外,您正在从“ messageBody”字段传递null。 Change null to "message is this" and see if it's working. 将null更改为“ message is this”,然后查看其是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM