Tuesday, January 6, 2015

Bind the dropdown list & select the required value in dropdownlist in ASP.Net MVC 4 Webgrid

I was struggling to select the value in dropdown. The value comes from database.

I dont think there is a straight way to achieve this unless we do a work around. (please update me if there is!!!)

The work around I did was...

in each collection which we use to bind dropdownlist use "selected=True" for the required value.

i know it sounds crazy, but we dont have any other choice (atleast I dont know any at this time).


It will be a extra step we need to do in controller after we bind the collection to one of the properties of the model.


(I cannot paste my code here...I am sorry)

The steps will be

1. Get the collection of items of the dropdown  [Ex: List<SelectListItem> (City/State)]

2. Iterate through each record of the model  [foreach (Employee emp in Employees)]

3. Assign the collection to the property of the model [Ex: emp.Cities=listCities]

4. Set the Selected property to true to the required value [Ex:- emp.Cities[x].Selected=true]


This is how I found the solution to my requirement. happy coding



Monday, January 5, 2015

Webgrid with Hidden PrimaryKey in ASP.Net MVC 4

It was very weird to know that we cannot have hidden column in webgrid.

Usually we keep Primary Key in hidden field/column in grids.

I successfully overcame this with the following logic.

The logic is :- Use the two fields [one label, one hidden] as HTML contols (one span, one hidden) in "grid.column"


grid.Column("RowNumber", format: item => rowNum = rowNum + 1),

grid.Column(null,header:"RoleName", style: "col4",
                 format:@<p>
                    <span>@item.RoleName</span>
                     <input type="hidden" id="DtoList[@(rowNum - 1)].RoleId" name="DtoList[@(rowNum - 1)].RoleId" value="@item.RoleId" />                    
                 </p>),



I couldn't find a way where we can combine  " RowNumber & Primary Key ".
That may be achievable, but I cannot spend time on that now.

It may help at least one another like me

happy coding..:-)