2013-06-11 16 views
9

Posiadam ProductController, który składa się z metody Create.Pobierz wiele zaznaczonych pól wyboru w MVC

My Model:

public class ProductEntry 
{ 
    public Crescent.LinqModel.Product Products { get; set; } 
    public ProductSKU SKUs { get; set; } 
    public List<SelectListItem> pColors { get; set; } 

    public ProductEntry() 
    { 
     pColors = new List<SelectListItem>(); 
    } 
} 

Tworzenie Get metoda:

public ActionResult Create() 
    { 
     CrescentAdmin.Models.ProductEntry product = new CrescentAdmin.Models.ProductEntry(); 
     var colors = _appData.GetProductColors().ToList(); 
     for (int i = 0; i < colors.Count; i++) 
     { 
      if (i == 0) 
       product.pColors.Add(new SelectListItem { Value = colors[i].Name.ToString(), Text = colors[i].Name, Selected = true }); 
      else 
       product.pColors.Add(new SelectListItem { Value = colors[i].Name.ToString(), Text = colors[i].Name }); 
     } 

     return View(product); 
    } 

to Kolory Chcę wypełnić listy wyboru, w którym można wybrać wiele checkboxes.its działa prawidłowo.

Tworzenie post:

[HttpPost] 
    [ValidateInput(false)] 
    public ActionResult Create(CrescentAdmin.Models.ProductEntry entry, HttpPostedFileBase uploadFile) 
    { 
     //code to insert in two table 
     // required to fetch which checkboxes are selected ??  
    } 

Tworzenie Widok:

 @model CrescentAdmin.Models.ProductEntry 

kod do listy wyboru wypełnić:

  <tr> 
      <td> 
       Product Colors 
      </td> 
      <td> 
       @if (Model.pColors != null && Model.pColors.Count > 0) 
       { 
        for (int i = 0; i < Model.pColors.Count; i++) 
        { 
         //if (Model.pColors[i]) 
         //{ 
          <input type="checkbox" value="@Model.pColors[i].Value" id="@Model.pColors[i].Value"/> @Model.pColors[i].Text <br /> 
          @Html.HiddenFor(m => Model.pColors[i].Value); 
          @Html.HiddenFor(m => Model.pColors[i].Text); 
          @Html.HiddenFor(m => Model.pColors[i].Selected); 
         //} 
         //else 
         //{ 
         // <input type="checkbox" value="@Model.pColors[i].Value" /> @Model.productColors[i].Name <br /> 
         //} 
        } 
       } 


       @Html.ValidationMessageFor(model => model.SKUs.ProductColors) 
      </td> 
     </tr> 

Próbowałem ten kod, ale bez powodzenia !!

wymagane do pobrania zaznaczonych pól wyboru? Proszę o pomoc

+0

Proszę pokazać swój widok – chamara

+0

Czy wypróbowałeś '@ Html.CheckBoxFor' – YesMan85

+0

@ Rogier21 - jak będę pisać w tym kontekście? – DharaPPatel

Odpowiedz

6

Spróbuj tego:

@Html.HiddenFor(m => Model.pColors[i].Value); 
@Html.HiddenFor(m => Model.pColors[i].Text); 
@Html.CheckBoxFor(m => Model.pColors[i].Selected); 
+0

to działało dla mnie, teraz jest w stanie wziąć liczbę zaznaczonych pól wyboru :) ale jeszcze jedno pytanie pomoże? – DharaPPatel

+0

Mam właściwości modelu, które są typu bitowego. Chcę umieścić pole wyboru i uzyskać metodę postu. Zrobiłem to kod: żydowski @ Html.CheckBox ("żydowski", new {id = "chkJewish"}) @ Html.ValidationMessageFor (model => model.SKUs.Jewish) ale na stanowisku nie dostaję pogoda jej wybraniu lub nie .. – DharaPPatel

+0

spróbować sama tu '@ Html.CheckBoxFor (model.SKUs.Jewish, new {id = "chkJewish"})' – karaxuna

0

Używam tego rozszerzenia:

public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, IEnumerable<TProperty>>> expression, 
    IEnumerable<SelectListItem> multiSelectList, 
    Object htmlAttributes = null) 
{ 
    // Derive property name for checkbox name 
    var body = expression.Body as MemberExpression; 
    if (body == null) 
     return null; 

    String propertyName = body.Member.Name; 

    // Get currently select values from the ViewData model 
    IEnumerable<TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model); 

    // Convert selected value list to a List<String> for easy manipulation 
    var selectedValues = new List<String>(); 

    if (list != null) 
     selectedValues = new List<TProperty>(list).ConvertAll(i => i.ToString()); 

    // Create div 
    var ulTag = new TagBuilder("ul"); 
    ulTag.AddCssClass("checkBoxList"); 
    ulTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true); 

    // Add checkboxes 
    foreach (var item in multiSelectList) 
    { 
     ulTag.InnerHtml += String.Format(
      "<li><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></li>", 
      propertyName, 
      item.Value, 
      selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "", 
      item.Text); 
    } 

    return MvcHtmlString.Create(ulTag.ToString()); 
} 
14

normalnie używam poniżej podejścia przy rozpatrywaniu wyboru sprawdzić, czy to pomaga.

Model:

namespace GateApplication.Models 
{ 
    public class Gate 
    { 
     public string PreprationRequired { get; set; } 
     public List<CheckBoxes> lstPreprationRequired{ get; set; } 
     public string[] CategoryIds { get; set; } 
    } 

    public class CheckBoxes 
    { 
     public int ID { get; set; } 
     public string Value { get; set; } 
     public string Text { get; set; } 
     public bool Checked { get; set; } 
    } 
} 

Kontroler:

obciążenia CheckBox Wartość:

public ActionResult Create() 
    { 
     List<CheckBoxes> lstchk = new List<CheckBoxes>() 
      { 
       new CheckBoxes {Text="coduit", Value="coduit" }, 
       new CheckBoxes {Text="safety", Value="safety" }, 
       new CheckBoxes {Text="power", Value="power" }, 
       new CheckBoxes {Text="access", Value="access" } 
      }; 

      var model = new Gate 
      { 
       lstPreprationRequired=lstchk 
      }; 

      return View(model); 
    } 

Widok:

@foreach (var item in Model.lstPreprationRequired) 
    { 
     <input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text"/> 
        <label for="optionId">@item.Text</label> 
     <br /> 
    } 

Teraz twój widok ma listę pól wyboru. Teraz zapisywanie wartości CheckBox do bazy danych.

[HttpPost] 
    public ActionResult Create(FormCollection collection) 
    { 
     try 
     { 

      Gate gate = new Gate(); 
      TryUpdateModel(gate); 

      if (ModelState.IsValid) 
      { 
       gate.PreprationRequired = Request.Form["CategoryIds"];// here you'll get a string containing a list of checked values of the checkbox list separated by commas 

       if (string.IsNullOrEmpty(gate.PreprationRequired))//this is used when no checkbox is checked 
        gate.PreprationRequired = "None,None"; 

       Save();//Save to database 
       return RedirectToAction("Index"); 
      } 
      else 
      { 
       return View(); 
      } 

     } 
     catch 
     { 
      return View(); 
     } 
    } 

Teraz masz poniżej rodzaju ciąg w bazie danych

bezpieczeństwa, moc, dostęp

Teraz pobrać wybrane wartości i wyświetlić widok.

public ActionResult Edit(int id) 
     { 
      List<CheckBoxes> lstchk = new List<CheckBoxes>() 
      { 
       new CheckBoxes {Text="coduit", Value="coduit" }, 
       new CheckBoxes {Text="safety", Value="safety" }, 
       new CheckBoxes {Text="power", Value="power" }, 
       new CheckBoxes {Text="access", Value="access" } 
      }; 

      var model = new Gate 
      { 
       lstPreprationRequired =lstchk, 
       CategoryIds = "safety,power,access".Split(',')//here get your comma separated list from database and assign it to the CategoryIds string array, i have used sample text for the values 
      }; 

      return View(model); 
     } 

Widok:

@foreach (var item in Model.lstPreprationRequired) 
     { 
      <input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text" 
      @foreach (var c in Model.CategoryIds) 
      { 
       if(c == item.Value) 
       { 
        <text> checked="checked"</text> 
       } 
      }/> 
      <label for="optionId">@item.Text></label> 
     } 

Daj mi znać, jeśli to nie pomoże.

+0

To było niesamowite :) –

1

Ja też był o scenariusz, jak ty i ja realizowane jest za pomocą EditorFor odwołując link „ASP.NET MVC - Multiple checkboxes for row selection in HTML table

do tego trzeba utworzyć folder EditorTemplate i trzeba dodać widok z samej nazwie modelu. Zobacz kod jak poniżej

@model EditorForSample.Models.ProductViewModel 


<tr> 
    <td class="text-nowrap">@Html.CheckBoxFor(m => m.Selected, new {@class="chkSelect"}) </td> 
<td colspan="3"> 
    @Model.Name 
    @Html.HiddenFor(m => m.Name) 
</td> 
<td> 
    @Model.Price 
    @Html.HiddenFor(m => m.Price) 
</td> 

model może być jak poniżej.

public class ProductPageViewModel 
{ 
    public string Message { get; set; } 

    public List<ProductViewModel> ProductsList { get; set; } 
} 

public class ProductViewModel 
{ 
    public bool Selected{ get; set; } 
    public string Name { get; set; } 
    public int Price { get; set; } 
} 

iw świetle dominującej można napisać html jak poniżej

....... 
    <div class="col-md-12"> 
     <table class="table table-bordered table-striped"> 
      <thead> 
       <tr> 
        <th><input type="checkbox" id="chkSelectAll" /></th> 
        <th colspan="3"> 
         Product Name 
        </th> 
        <th> 
         Cost 
        </th> 

       </tr> 
      </thead> 
      <tbody> 
       @Html.EditorFor(m => m.ProductsList) 
      </tbody> 
     </table> 
    </div> 
......... 

powyższy link zawiera przykładowy projekt zbyt. Wiem, że odpowiedź na to pytanie jest już zaakceptowana, ale po prostu dzielę się tym. To może komuś pomóc. Dzięki :-)

Powiązane problemy