Question: Why my MVC view passes null but not the value it has?

Question

Why my MVC view passes null but not the value it has?

Answers 1
Added at 2017-11-07 21:11
Tags
Question
  1. View shows proper value (OrderId = 3):

     // GET:
    public ActionResult ConfirmOrder()
    {
    
        //simplified code here
        var model = new ConfirmOrderViewModel()
        {
            OrderId = 3,
        };
    
        return View(model);
    }
    
  2. View works fine one way (value visible on the screen) Html-part below:

    @model Test.Models.Views.ConfirmOrderViewModel
    @{
        ViewBag.Title = "My title";
    }
    
    <h2>@ViewBag.Title</h2>
    
    
    @using (Html.BeginForm("ConfirmOrder", "Client", FormMethod.Post, new { 
    @class = "form-horizontal", role = "form" }))
    {
         @Html.AntiForgeryToken()
    
    
    <div class="row" style="padding:10px; margin:15px">
         <div>
              <div class="col-sm-3">
                   @Html.DisplayFor(m => m.OrderId)
              </div>
         </div>
    </div>
    
    }  
    
    1. ConfirmOrderViewModel class looks like this:

      public class ConfirmOrderViewModel
      {
             public int OrderId { get; set; }
      }
      

4. But when it comes to post it back, only null I'm having:

        // POST:
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ConfirmOrder(ConfirmOrderViewModel ViewModel)
        {
           //at this moment: ViewModel.OrderId = null 
             return RedirectToAction("Index");
        }

Controller Name is ok, Methods works... no errors. Just null after clicking the OK button on page. What can cause bad model binding here?

Answers to

Why my MVC view passes null but not the value it has?

nr: #1 dodano: 2017-11-07 21:11

The DisplayFor helper method will just render the value of the OrderId property. As the name suggests, It is more for displaying to the user. If you want the value for OrderId to be posted to the http post action method, you need to keep that in in a form field inside the form.

You can keep in a hidden field inside the form

@using (Html.BeginForm("ConfirmOrder", "Client"))
{  
    @Html.DisplayFor(m => m.OrderId)
    @Html.HiddenFor(a=>a.OrderId)
    <input type="submit" value="Confirm" />
}
Source Show
◀ Wstecz