2016-07-08 4 views
-1

heloo guys Viewbag 객체를 사용하여 mvc의 데이터베이스에서 dropdownlist를 채 웁니다. 이제 Select Supplier와 같은 기본값을 지정하고 싶습니다. 여기 내 제어 코드입니다. . 지정하는 방법 드롭 다운의 기본값은 MVC에서 Viewbag를 사용하여 데이터베이스에서 채워졌습니다

public ActionResult Create() 
    { 
     //IEnumerable<SelectListItem> SuppliersList = db.Suppliers.Select(c => new SelectListItem 
     //{ 
     // Value = c.Name, 
     // Text = c.Name 

     //});    

     ViewBag.SupplierList = new SelectList(db.Suppliers, "Name", "Name"); 
     return PartialView("_Create"); 
    } 

    // POST: /Frames/Create 
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Create([Bind(Include="FrameId,Name,FrameCode,FrameFor,Brand,Material,Color,FrameType,FrameShape,Bridge,LensWidth,FrameWidth,TempleLength,LensHeight,FrameWeight,Quantity,PurchaseRate,SaleRate,Supplier,Discription,Status,CreatedOn")] Frame frame) 
    { 

     if (ModelState.IsValid) 
     { 
      db.Frames.Add(frame); 
      await db.SaveChangesAsync(); 
      return Json(new { success = true }); 
     } 



     return PartialView("_Create", frame); 
    } 

내 ViewCode 당신이 ViewBag 및 DropDownList HTML 도우미 방법을 사용하는 경우

<div class="col-md-3"> 
        @Html.LabelFor(model => model.Supplier) 
        @Html.DropDownList("Supplier", ViewBag.SupplierList as SelectList, new { @class = "form-control"}) 
        @Html.ValidationMessageFor(model => model.Supplier) 
       </div> 

답변

0

, 당신은 선택한 항목의 이름 (사인은 당신이 선택에 대한 값 속성으로 이름을 사용 설정해야합니다 Lis t) ViewBag.Supplier으로 여기에 DropDownList 도우미 메서드의 첫 번째 매개 변수에 사용 된 값입니다.

var suppliers = db.Suppliers.ToList(); 
ViewBag.SupplierList = new SelectList(suppliers , "Name", "Name"); 
// Here i am setting the 2 item in suppliers as the selected item. 
// You can change it as needed 
ViewBag.Supplier = suppliers[1].Name; 
return PartialView("_Create"); 

당신이 기본을 표시 할 경우 드롭 다운 옵션과 함께 옵션, 당신은 DropDownList 방법이 오버로드를 사용할 수있다 "를 선택하십시오."

public static MvcHtmlString DropDownList(
    this HtmlHelper htmlHelper, 
    string name, 
    IEnumerable<SelectListItem> selectList, 
    string optionLabel, 
    object htmlAttributes 
) 

그래서 코드는 또 다른 해결책은 viewbag를 사용하여 강력한 형식의 뷰 모델을 사용하고 Html.DropDownListFor 도우미 메서드를 사용하지 않는 것입니다

@Html.DropDownList("Supplier", ViewBag.SupplierList as SelectList, 
             "Please select", new { @class = "form-control" }) 

될 것입니다. Here은이를 수행하는 방법의 예입니다.

0

optionLabel 무시를 구현하기 만하면됩니다.

@Html.DropDownList("Supplier", 
        ViewBag.SupplierList as SelectList, 
        "Select Supplier", 
        new { @class = "form-control" }) 
+0

Shyju와 JamieD77이 너무 감사합니다. Jamie Soloution을 다시 사용해 주셔서 감사합니다. – Imran

관련 문제