Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specify name and id to Drop down razor technique asp dot net mvc4

I have asp web form and i'm using razor technique to post that form, problem is that, i want to know that how to specify ID and NAME attribute to razor dropdown list because, in next step, i'm getting the form value by using the ID and NAME attribute..

VIEW code is :

@Html.DropDownList("ID", (SelectList) ViewBag.list, " -- Select Business Type -- ")

CONTROLLER:

public ActionResult coverage()
{
    var query = db.Database.SqlQuery<businessDropDownModel>("businesDropDownSP");
    ViewBag.list = new SelectList(query.AsEnumerable(), "ID", "BusinessTypeName", "----select----");

    return View();
}

MODEL:

public class businessDropDownModel
{
    public int ID { set; get; }
    public string BusinessTypeName { set; get; } 
}
like image 761
Rahil Avatar asked Oct 12 '13 09:10

Rahil


People also ask

How do I populate a DropDownList based on another dropdown selected value?

You will have to simply execute the script named CreateCascadingDatabase. sql stored in the SQL Folder of the attached sample and it will create the complete database with data. Below is the HTML Markup which contains three ASP.Net DropDownList controls each for Country, State and City.


3 Answers

If you want to set the name and id or other attributes you can use the html attributes option.

NOTE: the method has a quirk: you can use the attributes dictionary to override the "id", but not the "name".

example:

@Html.DropDownList("Selected", Model.SelectList, "First Option", new { name = "Name", id = "id"})

will render:

<select id="id" name="Selected">...</select>

So the upshot is: if you want name and id to be different, set the name parameter to what you want the name to be, and use the dictionary to override the id.

like image 86
Matt Bodily Avatar answered Nov 23 '22 17:11

Matt Bodily


The first argument in @Html.DropDownList("MyIdAndName", (SelectList) ViewBag.list, " -- Select Business Type -- ") is both the id and the name of the select tag.

So,

@Html.DropDownList("MyIdAndName", (SelectList) ViewBag.list, " -- Select Business Type -- ")

would render

<select id="MyIdAndName" name="MyIdAndName">...</select>
like image 21
JLe Avatar answered Nov 23 '22 18:11

JLe


If you need to set the Id to something different than the Name, you can use the htmlAttributes parameter to set the Id of the control. You still use the first parameter in the DropDownList helper to set the Name of the control.

@Html.DropDownList( "Job.DefaultProfitCenter", (SelectList)ViewBag.DefaultProfitCenter, " -- Select -- ", new { id = "Job_DefaultProfitCenter" } )

This will generate the following html for the drop down list:

<select id="Job_DefaultProfitCenter" name="Job.DefaultProfitCenter">
    <option value=""> -- Select -- </option>
    <option value="0">Option 1</option>
</select>
like image 26
randyh22 Avatar answered Nov 23 '22 18:11

randyh22