Список флажков всегда нулевой MVC - PullRequest
0 голосов
/ 09 октября 2018

У меня проблемы с отправкой значений checkboxes и EditorFor в MVC.У меня есть два класса:

public class CompleteReceiving
 {
   public List<SiteOrderReceiving> order_detail { get; set; } //<- Data from DB. It contains all items for Order Receiving.
   public List<SomeClass> new_form { get; set; } //<- Fields for form
 }  

public class SomeClass
 {
        [RegularExpression("^[0-9]*$", ErrorMessage = "Receive Quantity can only contain number")]
        public decimal? receive_quantity { get; set; }

        [RegularExpression("^[0-9]*$", ErrorMessage = "Damaged Quantity can only contain number")]
        public decimal? damaged_quantity { get; set; }  

        public bool IsSelected { get; set; }
 }

Это мой взгляд:

    @for(int i = 0; i < Model.order_detail.Count; i++)
     {  
      <tr> 
        <td>@Html.CheckBoxFor(m => m.new_form[i].IsSelected, new { id = "site_rec_checkbox", @class= "site_rec_checkbox" })
       </td>  
       <td>@Html.EditorFor(m => m.new_form[i].receive_quantity, new { htmlAttributes = new { @class = "form-control fm", @autocomplete = "off", @autofocus = "autofocus", @placeholder = "Receiving Quantity" } })
         @Html.ValidationMessageFor(m => m.new_form[i].receive_quantity, "", new { @class = "text-danger" })
       </td>  
     }  

И это мой код действия контроллера:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SiteOrderReceiving(CompleteReceiving sor)
 {
     //Code for post
 }  

Проблема в том, что всякий раз, когдая выбираю checkbox в любом другом index, чем 1 или 2, List всегда null.Но в первый раз, если я выберу 3 или 4, и после этого я выберу 1 или 2, это будет работать нормально.Я не знаю, что я делаю здесь неправильно.
Любая помощь будет принята с благодарностью.

Обновление
Это мой контроллер Action Code

 [HttpGet]
 public ActionResult SiteOrderReceiving(int? order_id)
 {
   var get_detail = (from oa in db.order_send
                     where oa.order_id == order_id 
                     select new SiteOrderReceiving()
                     {
                       quantity_send = oa.send_quantity,
                       date_send = oa.send_date,
                       order_id = oa.order_id
                     }).ToList();
  var a = new CompleteReceiving();
  a.order_detail = get_detail;
  return View(a);
}  

А это мой View

@using (Html.BeginForm("SiteOrderReceiving", "Site", FormMethod.Post, new { id = "receive_form" }))
{
  @Html.AntiForgeryToken();
  @Html.ValidationSummary(true, "", new { @class = "text-danger" })

@for(int i = 0; i < Model.order_detail.Count; i++)
{  
 <tr> 
     <td>@Html.CheckBoxFor(m => m.new_form[i].IsSelected, new { id = "site_rec_checkbox", @class= "site_rec_checkbox" })
     </td>  
     <td>@Html.EditorFor(m => m.new_form[i].receive_quantity, new { htmlAttributes = new { @class = "form-control fm", @autocomplete = "off", @autofocus = "autofocus", @placeholder = "Receiving Quantity" } })
         @Html.ValidationMessageFor(m => m.new_form[i].receive_quantity, "", new { @class = "text-danger" })
     </td>  
  } 

}

1 Ответ

0 голосов
/ 09 октября 2018

Итак, я решил свою проблему.Я переместил свойства моего form в существующий класс, в который я получал данные из DB.
Теперь мой ViewModel выглядит следующим образом:

public class CompleteReceiving
{
  public List<SomeClass> order_detail { get; set; }  
  //Some Other properties
} 

И затем:

public class SomeClass
{  
   [RegularExpression("^[0-9]*$", ErrorMessage = "Receive Quantity can only contain number")]
   public decimal? receive_quantity { get; set; }

   [RegularExpression("^[0-9]*$", ErrorMessage = "Damaged Quantity can only contain number")]
   public decimal? damaged_quantity { get; set; }  

   public bool IsSelected { get; set; }    

   public string item_name { get; set; }
} 

После обновления моего code, как указано выше, все начало работать нормально.Надеюсь, это поможет кому-то в будущем.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...