0

i used value the model for drop down list,

> public class Items
>     {
>         public int itemcategoryid { get; set; }
>         public string itemcategory { get; set; }
>         public int Itemsubcategoryid { get; set; }
>         public string Itemsubcategoryname { get; set; }
>     }

and below the code for controller

>             ItemViewModel catVM = new ItemViewModel();
>             List<Items> catlist = catVM.GetCategoryInfo();
>             ViewBag.categorylist = catlist;

After binding drop down list using below the HTML code, the drop down list has populated and select default name as itemcategory but did not pass id of itemcategory pass only itemcategory name for POST.

 @Html.DropDownListFor(model => model.itemcategory, new SelectList(ViewBag.categorylist, "itemcategory", "itemcategory",  Model.itemcategory))

if i using below the HTML Code their pass value but did not select default name

  @Html.DropDownListFor(model => model.itemcategory, new SelectList(ViewBag.categorylist, "itemcategoryid", "itemcategory", Model.itemcategory))

using below the code for retrieve data

using (OracleCommand cmd = new OracleCommand("PS_Category", conn))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    conn.Open();
                    OracleDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        Items listitems = new Items(); ;
                        listitems.itemcategoryid = Convert.ToInt32(reader["CATID"]);
                        listitems.itemcategory = reader["CATNAME"].ToString();
                        items.Add(listitems);
                    }
                }

Actually i want to to select default name and pass their id how can possible it??

brids
  • 25
  • 2
  • 11
  • Will you include the code of the function `catVM.GetCategoryInfo();`? – Jerdine Sabio Nov 25 '19 at 02:30
  • this is code for data retrieve from database, and also edited my question and include this code – brids Nov 25 '19 at 03:02
  • Oh, okay. I understood your question just now, you want to select the default value. What is the class you are using for `model` in the view? – Jerdine Sabio Nov 25 '19 at 03:24
  • Is model.itemcategory the id or the name in your model class? – Jerdine Sabio Nov 25 '19 at 03:25
  • my model class @model Webapps8.Models.Items , itemcategory is name, and itemcategoryid is id, – brids Nov 25 '19 at 03:27
  • Just curious, why are you using model.itemcategory in your DropdownListFor— when you mentioned you should be passing the id? Shouldnt it be model.itemCategoryId? – Jerdine Sabio Nov 25 '19 at 03:41
  • i used both itemcategoryid and i itemcategory in model, actually i need select itemcategory as default value and pass id of itemcategory which are named itemcategoryid – brids Nov 25 '19 at 03:57
  • this code i used for edit function, when i clicked edit drop down list retrieve data from db and populate ,, – brids Nov 25 '19 at 04:00

2 Answers2

0

This was answered here before but some are reporting that it doesn't work for them; @Html.DropDownListFor how to set default value


If that doesn't work, the selectlist class documentation is here

https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.selectlist.-ctor?view=aspnet-mvc-5.2#System_Web_Mvc_SelectList__ctor_System_Collections_IEnumerable_System_String_System_String_System_String_System_Object_

It is mentioned there that the constructor you used uses the last parameter as the selected value, hence you should do; (pass model.itemcategoryid in the end)

@Html.DropDownListFor(model => model.itemcategory, new SelectList(ViewBag.categorylist, "itemcategoryid", "itemcategory", Model.itemcategoryid))

If the above answer doesn't work for you, here's another way but using jquery;

  1. Add a class htmlattribute selectLoop;
@Html.DropDownListFor(model => model.itemcategoryId, new SelectList(ViewBag.categorylist, "itemcategoryid", "itemcategory"), new { @class="selectLoop" })
  1. Add this script to your view;
@section scripts{
 <script>
 // when the document is ready (server is done loading)
 $(document).ready(function(){

   // loop through all those with selectLoop class
   $(".selectLoop").each(function(){

      // get the selected value and store to variable
      var selected = "@Model.itemCategoryId";

      // loop through all the option inside the select
      $(this).find("option").each(function(){

         // check if the value attribute matches the selected variable
         if($(this).attr("value") == selected){

            // if match, assign the option's selected attribute to true
            $(this).attr("selected",true);
         }
      });
   });
 });
 </script>
}

Then in your shared/layout.cshtml, add @RenderSection("scripts", required: false) after jquery and bootstrap. See below;

  @Scripts.Render("~/bundles/jquery")
  @Scripts.Render("~/bundles/bootstrap")
  @RenderSection("scripts", required: false)
Jerdine Sabio
  • 5,688
  • 2
  • 11
  • 23
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/203136/discussion-on-answer-by-jerdine-sabio-selecte-default-value-in-dropdown-list-and). – Samuel Liew Nov 26 '19 at 22:15
0

For Multiple dropdown Value You Use It.For Insert Value

ViewBag.DocumentId = new SelectList(_documentCategoryService.GetAll().OrderBy(a => a.Name), "Id", "Name");

For Edit You Can Use this.

ViewBag.DocumentId = new MultiSelectList(_documentCategoryService.GetAll(), "Id", "Name", _documentCategoryService.GetAllByExportId((int)id).Select(a => a.DocumentCategoryId).ToArray());

View Part:

 <div class="row-fluid">
                <div class="span12">
                    <div class="control-group">
                        <label class="control-label">Documents Require</label>
                        <div class="controls controls-row">
                            @Html.DropDownList("DocumentId", null, htmlAttributes: new { @placeholder = "Select Documents", @class = "span6 chzn-select documentCategories", @tabindex = "8", @multiple = "multiple", @name = "DocumentId" })
                        </div>
                    </div>
                </div>
            </div>

For Single DropdownValue.

ViewBag.BranchId = new SelectList(_branchService.GetAllByOrganizationId((User as CustomPrincipal).DefaultOrganizationId), "Id", "Name");


ViewBag.BranchId = new SelectList(_branchService.GetAllByOrganizationId((User as CustomPrincipal).DefaultOrganizationId), "Id", "Name", exportLetter.LcTransctionDetails.Transactions.BranchId);

<div class="span4">
                    <div class="control-group">
                        <label class="control-label">Branch</label>
                        <div class="controls controls-row">
                            @Html.DropDownList("BranchId", null, htmlAttributes: new { @class = "form-control", @id = "Branches" })
                        </div>
                    </div>
                </div>