How to set Default value in MVC 4 razor DropDownListFor - asp.net-mvc-4

I Have MVC Razor view with lot of DropDrownFor.
i wanna set default value to that DropdownListFor.
This is my View:
#Html.DropDownListFor(model => model.DestCountryId, ViewBag.CountryIdList as SelectList, "select", new { #class = "form-control input-sm" })
This is my ViewBag:
ViewBag.CountryIdList = new SelectList(db.Countries.Where(a => a.Currency != null), "Id", "Name");
Ho w to set Default value in this scenario

you need to do like this:
ViewBag.CountryIdList = new SelectList(db.Countries.Where(a => a.Currency != null), "Id", "Name",1);
For Example in the Countries List, you have a item CountryName and its id is 1, you need to pass the 1 in the last parameter, and element with that Id 1 will be shown selected by default.
Example:
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
List<Country> list = new List<Country>();
list.Add(new Country{ Id = 1, Name="Test"});
list.Add(new Country{ Id = 2, Name="Test2"});
now in controller action:
int Selected = 2;
ViewBag.CountryIdList = new SelectList(list, "Id", "Name",Selected);
Now the Test2 will be shown selected default in View.

The first parameter that you give to #Html.DropDownListFor is an expression that identifies the object that contains the properties to display.
You have already given "Selected" as default value if nothing is selected or your DestCountryId doesn't hold any value or it doesn't matches with the values passed in the CountryIdList. You need to assign a value to DestCountryId before rendering this view. You can do this either in controller or where you build your view-model like:
viewModel.DestCountryId = 33; where this value exists in the selectList value that you are giving to dropdownlist.
Also, a good practise is to not to use ViewBag. Try creating a simple model with properties that your current view needs.
You can also use SelectList(IEnumerable, String, String, Object) overload of SelectList where the object is the selected value.
Hope this helps.

Related

Can I set value=1 item in dropdown as default item

ViewBag.UserStatusList = new List<SelectListItem>
{
new SelectListItem{Text = "Active", Value = "1",Selected=true},
new SelectListItem { Text = "Inactive", Value = "0",Selected=false }
};
the above shows the viewbag which i am binding to dropdown list . So here I want to fix Active as default item in the view page. How can I do that please give some suggestions
#Html.DropDownListFor(m => m.UserStatus, (IEnumerable<SelectListItem>)ViewBag.UserStatusList, new { #id = "ddlCustomerStatusList", #class = "form-control", #selected = "selected" })
This is my view
You need to set the value of your model property in the GET method before you return the view
model.UserStatus = 1;
return View(model);
You can delete setting the Selected property of SelectListItem because its ignored by the DropDownListFor() method (internally the method builds a new IEnumerable<SelectListItem> based on the value of the property your binding to)
Note also you should delete new { #selected = "selected" }(that is not a valid attribute for a <select> element) and there is no need to use new { #id = "ddlCustomerStatusList" } as the helper already creates an id attribute (its id="UserStatus")

MVC4 .Net How to place DropDown in WebGrid Cell

I have seen a number of questions that are similar to this one, but I have not come across one with an answer that works for me. Yet :)
My Model looks like this:
public class MyModel
{
public List<MyItem> MyItems{get;set;}
public List<SelectListItem> MySet{get;set;}
}
MyItem looks like this:
public class MyItem
{
public int MyItemId
}
My view has #model MyModel at the top.
My WebGrid looks like this:
#{
var grid = new WebGrid( Model.MyItems, canPage: false );
var gridColumns = new List<WebGridColumn>
{
grid.Column(
format: (item) => #Html.DropDownListFor(modelItem => item.MyItemId.ToString(), Model.MySet ) )
};
#grid.GetHtml( "wgtable",
rowStyle: "gridrow",
alternatingRowStyle: "altgridrow",
displayHeader: true,
columns: grid.Columns( gridColumns.ToArray( ) ) )
}
In this case, the error I get is CS1963: An expression tree may not contain a dynamic operation.
I have also tried
format: (item) => #Html.DropDownListFor(item.MyItemId.ToString(), Model.SubPayGroups ) )
which gives me CS1973: Model has no applicable method named 'DropDownListFor'.
Am I even close?
I ended up moving away from DropDownListFor, using DropDownList instead, also building an IEnumerable: this was my final working solution for the column:
grid.Column(
header:"Sub Pay Group",
format: (item) => #Html.DropDownList("MyItemId", Model.MySet.Select( u => new SelectListItem
{
Text = u.Text,
Value = u.Value,
Selected = u.Value == ((WebGridRow)item)["SubPayGroupId"].ToString() }),
It wasn't in my initial problem definition, but I also needed to set a selected item. Thus, the additional Select from MySet...

how to set the selected value in the drop down list populated with ViewData in mvc

I am new to MVC, please help me to set the selected value in drop down list populated using View Data. I have gone through so many solutions but every solutions deals with selecting value for single drop down. I have same drop down listed using the foreach loop. Setting selected value for each dropdown in that foreach loop.
My code is shown below.
[In view]
int i = 0;
foreach (var item in Model.Select((x, j) => new { Data = x, Index = j + 1 })) {
#Html.DropDownListFor(model => item.Data.CategoryID,(IEnumerable<SelectListItem>)ViewData["categories"], new { #id = "category" + i })
i++;
}
[in controller]
SelectList selectList = new SelectList((IEnumerable<Category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName");
ViewData["categories"] = selectList;
There is a lot missing from your sample (e.g.what a category looks like, what the Edit actions look like, what is dt1, what the model is you pass to the view etc), but I will try based on what is shown.
Problem 1: Can't use foreach in binding
You can't use a foreach with a collection of form items. The items have no way of knowing which individual element to bind with (when they are sent back to the server they need more information to make each entry unique).
Solution:
It only knows how to bind if you use indexing (e.g. using for (int i=0; < count; i++){ #Html.DropDownListFor(model=>item[i]...)
Problem 2: Selected values only can come from SelectList!
This is the most irritating feature of DropDownListFor and appears to be a bug. It will not take the current selected value from the bound data. It will only take a current value from a SelectList, which means you need a unique SelectList for every dropdown.
Solution:
Create a unique SelectList in the view, per drop down required, with the item value as the current selection.
With some faking of your data, I got the following working:
Example
Controller:
Only store the list of items for the SelectList in the ViewBag:
ViewData["categories"] = ConvertCategoryToList(dt1);
View:
1. You need to pass a List and not an IEnumerable as IEnumerable cannot be indexed.
#model List<MyApplication.Item>
2. Create a SelectList for each dropdown
SelectList newSelectList = new SelectList((IEnumerable<MyApplication.Category>)ViewData["categories"], "CategoryID", "CategoryName", Model[i].Id);
3. Use the indexing method for addressing your items in the collection.
#Html.DropDownListFor(m => Model[i].Id, newSelectList, "Select an item")
Problem 3: What data to pass?
The other issue with your code, as-it-stands, is what to pass back and forth to/from the edit view? At the moment I would guess (from the variable name dt1) you are passing a DataTable(?). You will need to be very explicit about the data you are using in order to get a clean solution to this one. I would suggest posting a second question with all your code and Razor view HTML.
If you need to see more of my sample code (below), please post your own code so I can make them consistent.
Full dummy controller code below
public class TestController : Controller
{
public List<Category> dt1 { get; set; }
public TestController()
{
this.dt1 = new List<Category>();
for (int i = 1; i <= 10; i++)
{
this.dt1.Add(new Category() { CategoryId = i, CategoryName = string.Format("Category {0}", i) });
}
}
[HttpGet]
public ActionResult Edit()
{
//SelectList selectList = new SelectList((IEnumerable<Category>)ConvertCategoryToList(dt1), "CategoryID", "CategoryName");
ViewData["categories"] = ConvertCategoryToList(dt1);
List<Item> items = new List<Item>();
items.Add(new Item(){Id = 1});
items.Add(new Item(){Id = 2});
items.Add(new Item(){Id = 3});
items.Add(new Item(){Id = 4});
items.Add(new Item(){Id = 5});
return View(items);
}
[HttpPost]
public ActionResult Edit(FormCollection form)
{
// Turn form submission back into a compatible view model
List<Item> items = new List<Item>();
foreach (string key in form.Keys)
{
string val = form[key];
items.Add(new Item() { Id = int.Parse(val) });
}
// Recreate the select list
ViewData["categories"] = ConvertCategoryToList(dt1);
return View(items);
}
List<Category> ConvertCategoryToList(IEnumerable<Category> dt)
{
return dt.ToList();
}
}
Note: The post version of Edit simply recreates the list of data (using the selected values posted back) and returns to the Edit view. This is just for testing.
Screen shot
Dummy category class
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
Full test View
#model List<MyApplication.Item>
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
SelectList newSelectList = new SelectList((IEnumerable<MyApplication.Category>)ViewData["categories"], "CategoryID", "CategoryName", Model[i].Id);
#Html.DropDownListFor(m => Model[i].Id, newSelectList, "Select an item")
}
<input type="submit" value="Submit"/>
}

In Update view, the dropdown selected value is not set if the selected field is nullable in viewmodel

Say for example my viewmodel is as follows:
public class MyViewModel
{
public int? SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
And the view is as follows:
#model MyViewModel
#Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories,
"--Select--"
)
In the update view, if the model has a value for the SelectedCategoryId it is not shown selected in the dropdownlist. The "--Select--" is always selected. The same logic works for other dropdownlist if their Id field are not nullable.
Any suggestions?
Suggesting you a simple approach.
If you are using IEnumerable <SelectListItem> then there is no need to user different variable for Maintaining Selected value.. Just mark your category selected when you are populating Categories SelectList.
SelectListItem category = new SelectListItem
{
Text = "CategoryId",
Value = "CatagoryName",
Selected = true
};
Categories.Add(category);
public class MyViewModel
{
public IEnumerable<SelectListItem> Categories { get; set; }
}
..............................................
#model MyViewModel
#Html.DropDownList("Name",
Model.Categories,
"--Select--"
)
In the end I used jquery to select the dropdown if the Id has a value.
In the view, I create a hidden field (don't use the #Html.HiddenFor)
#Html.Hidden("SelectedCategorySubId", Model.SelectedCategorySubId.GetValueOrDefault(), new { #id = "hdnSelectedCategorySubId" })
In JS file,in the call back method of ajax call (to load the drop down),after adding data to dropdown, get the hidden field value and then select that value in dropdown.
$.ajax({
type: 'POST',
url: "GetSubCategory",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(param),
success: function (subCategoryList) {
if (subCategoryList != null && subCategoryList != '') {
$("#SelectedCategorySubId").append('<option>--- Select ---</option>');
$.each(subCategoryList, function (i, subCategory) {
$("#SelectedCategorySubId").append($('<option/>', {
value: subCategory.Value,
text: subCategory.Text
}));
});
//Set selected value from hidden field
var selectedCategorySubId = $("#hdnSelectedCategorySubId").val();
// alert("Sub Cat" + selectedCategorySubId);
$("#SelectedCategorySubId").val(selectedCategorySubId);
}//end if
else {
//alert("empty subcategoryList " + subCategoryList);
$("#tdSubCategory").hide();
}
}
And update the hidden field if the dropdown changes
//Update hidden field, if cat changes
$("#SelectedCategorySubId").change(function () {
$("#hdnSelectedCategorySubId").val($(this).val());
});
I hope this helps someone.

How to get the selected value of a dynamically created selectlist component

I am not sure whether this is even possible, but I am trying to get the values of dynamically created selectlists in a VisualForce Apex controller class.
I am dynamically creating a selectlist for each field in a particular object (e.g. Contact) using the code below, but now I do not know how to get the selected value back. I have tried setting the value of each in the constructor and on a separate line (not in code sample below), but this does not seem to work.
VisualForce page:
<apex:dynamicComponent componentValue="{!contactPageBlockSection}" />
Apex controller:
public Component.Apex.PageBlockSection GetContactPageBlockSection(string objectName)
{
Map<string, Schema.SObjectField> FieldMap;
FieldMap = Schema.SObjectType.Contact.fields.getMap();
Set<string> FieldSet = FieldMap.keySet();
List<string> FieldList = new List<string>();
FieldList.addAll(FieldSet);
FieldList.sort();
Component.Apex.PageBlockSection pbs = new Component.Apex.PageBlockSection(columns = 2);
for (string fieldName : FieldList)
{
Component.Apex.PageBlockSectionItem pbsi = new Component.Apex.PageBlockSectionItem();
Schema.DescribeFieldResult field = (FieldMap.get(fieldName)).getDescribe();
if (field.isUpdateable() && field.IsAccessible())
{
Schema.DisplayType dt = field.getType();
Component.Apex.OutputLabel lblText = new Component.Apex.OutputLabel(escape = false);
lblText.value = field.getLabel();
pbsi.childComponents.add(lblText);
Component.Apex.SelectList selList = new Component.Apex.SelectList(id = field.getName(), multiselect = false, size = 1, style = 'width:200px;');
if (dt == Schema.DisplayType.Integer || dt == Schema.DisplayType.Double || dt == Schema.DisplayType.Currency || dt == Schema.DisplayType.Percent)
{
AddSelectOption(selList, 'Keep highest value');
AddSelectOption(selList, 'Keep lowest value');
AddSelectOption(selList, 'Keep master value');
pbsi.childComponents.add(selList);
pbs.childComponents.add(pbsi);
}
}
}
return pbs;
}
private void AddSelectOption(Component.Apex.SelectList selList, string option)
{
Component.Apex.SelectOption selOption = new Component.Apex.SelectOption();
selOption.itemLabel = option;
selOption.itemValue = option;
selList.childComponents.add(selOption);
}
Many thanks in advance
just bind the value attribute of the dynamically created select list to a string property using expression syntax like:
String selectedValue {get; set;}
...
setList.expressions.value = '{!selectedValue}';
the property should then store the selected value just as it would in a static declarative definition of the select list.
You could try and use dynamic visualforce binding. I.E.
map<String,String> FieldToString {get; set;}
...
selList.expressions.value = '{!FieldToString[\'' + fieldname + '\']}';
However, I have never used dynamic visualforce bindings within dynamic visualforce so caveat emptor.