簡體   English   中英

將數據從View傳遞到控制器(MVC 3)

[英]Passing data from View to Controller (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>
  }`    

“消息”始終為空...請您能幫我嗎?

像這樣更改您的控制器方法:

[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”,然后查看其是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM