Confused about how to Populate DropDown thru ViewBag - asp.net-mvc

I am a beginner to ASP.NET MVC technology. In my controller page I am using this code below
[HttpGet]
public ActionResult UrunEkle() {
List<SelectListItem> degerler = (from i in db.tblKategoriler.ToList()
select new SelectListItem
{
Text = i.KategoriAd,
Value = i.KategoriId.ToString()
}).ToList();
ViewBag.dgr = degerler;
return View(degerler);
}
this is view page
model MVCSTOK.Models.Entity.tblKategoriler
<div>
<label>Ürün Kategori</label>
#Html.DropDownListFor(m=>m.KategoriAd,(List<SelectListItem>)ViewBag.dgr, new { #class = "form-control" });
</div>
I am geting this error
The model item passed into the dictionary is of type System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]', but this dictionary requires a model item of type 'MVCSTOK.Models.Entity.tblKategoriler.

Your returning data's type isn't corresponding to MVCSTOK.Models.Entity.tblKategoriler, that you return it from UrunEkle() Action method. You return List<SelectListItem>, but your View's type of model is MVCSTOK.Models.Entity.tblKategoriler.
I think you can do (return view without model):
[HttpGet]
public ActionResult UrunEkle() {
List<SelectListItem> degerler = (from i in db.tblKategoriler.ToList()
select new SelectListItem
{
Text = i.KategoriAd,
Value = i.KategoriId.ToString()
}).ToList();
ViewBag.dgr = degerler;
return View();
}
And you can do this in .cshtml view (without model):
<div>
<label>Ürün Kategori</label>
#Html.DropDownListFor(m=>m.KategoriAd,(List<SelectListItem>)ViewBag.dgr, new { #class = "form-control" });
</div>

Related

How can I get the selected item from dropdownlist in controller?

#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.DropDownListFor(model => model.td_company_name, ViewBag.Listcompany as IEnumerable, new { #class = "form-control" }) }
The selected value is bound to the ViewModel property you define in the expression you pass as first parameter to DropDownListFor. In the example you have given this would be td_company_name. To get the selected item, retrieve it from the available options using the selected value.
[HttpPost]
public ActionResult MyPostAction(td_company model) {
var selectedValue = model.td_company_name;
IEnumerable<SelectListItem> availableOptions = Listcompany();
SelectListItem selectedItem = availableOptions.Single(opt => opt.Value == selectedValue);
// ...
}

Html.DropDownFor: Templates can be used only with field access, property access, single-dimension

Updated:
#Html.DropDownListFor(m = item.SelectedType, (IEnumerable<SelectListItem>)ViewBag.DropDownLoadRecoveryType, new { #class = "form-control"
Why am I getting this error:
Templates can be used only with field access, property access,
single-dimension array index, or single-parameter custom indexer
express
I have scan all the questions here before posting and I'm stuck and I need help please.
here is my model:
public string SelectedType { get; set; }
here is my controller:
public static class RecoveryTypesDropDown
{
public static IEnumerable<SelectListItem> RecoveryTypes { get; set; }
}
public void DropDownLoadRecoveryType()
{
using (var context = new salt_entities())
{
var list = context.Types.OrderBy(b => b.Sort).ToList().Select(e => new { e.ID, e.Type });
IEnumerable<SelectListItem> lists = list.Select(b => new SelectListItem { Value = b.ID.ToString().Trim(), Text = b.Type.Trim() }).ToList();
RecoveryTypesDropDown.RecoveryTypes = lists;
}
}
public ViewResult Collection(Guid id)
{
ViewBag.DropDownLoadRecoveryType = RecoveryTypesDropDown.RecoveryTypes;
//....
foreach (var item in collectionViewModelList)
{
//....
collectionViewModel.SelectedType = item.Type.Value;
}
}
here is my .html razor code:
#model IEnumerable<myapp.Models.CollectionViewModel>
#foreach (var item in Model)
{
#Html.DropDownList(item.SelectedType.Trim(), (IEnumerable<SelectListItem>)ViewBag.DropDownLoadRecoveryType, new { #class = "form-control" })
}
Your initial problem is use of .Trim() in the html helper. As the message states, the helper needs to access a property, but the use of .Trim() means it accessing a method on the property (not the property itself), hence the exception.
In addition you should not be using static properties (not thread safe). But the main problem you have is that your not constructing your html properly and generating duplicate id attributes (invalid html) and name attributes by using a foreach loop so binding will fail. Instead use a custom EditorTemplate for typeof CollectionViewModel
View/Shared/EditorTemplates/CollectionViewModel.cshtml
#model CollectionViewModel
#Html.DropDownListFor(m => m.SelectedType, (SelectList)ViewData["RecoveryTypes"], new { #class = "form-control" })
// other controls for properties of CollectionViewModel
and in the main view
#model IEnumerable<CollectionViewModel>
#using(Html.BeginForm())
{
#Html.EditorFor(m => m, new { RecoveryTypes = ViewBag.RecoveryTypes })
<input type="submit" />
}
In the controller
public ViewResult Collection(Guid id)
{
var list = context.Types.OrderBy(b => b.Sort);
ViewBag.RecoveryTypes = new SelectList(list, "ID", "Type");
IEnumerable<CollectionViewModel> model = ??
....
return View(model);
}
[HttpPost]
public ViewResult Collection(IEnumerable<CollectionViewModel> model)
{
// save and redirect
}
Note the html will now include indexers so the collection can be bound when you post back
<select name="[0].SelectedItem" ....>
<select name="[1].SelectedItem" ....>
If the value of property SelectItem matches the value of one of the options your generating, then that item will be selected when you first render the page.

unable to bind dropdownlist in mvc using viewmodel property

In my viewmodel I've a getter property as below.
[Display(Name = "Users System:")]
public string UsersSystem { get; set; }
public IEnumerable<SelectListItem> SystemsList
{
get
{
List<SelectListItem> lst = new List<SelectListItem>();
string[] UsersSystem = ConfigurationManager.AppSettings["UsersSystem"].ToString().Split(new char[] { ',' });
foreach (var item in UsersSystem)
{
lst.Add(new SelectListItem { Text = item, Value = item });
}
return lst;
}
}
I need to bind the values to a dropdownlist but I m getting Object reference not set to an instance of an object. My view has the following mark up
#model GazetteerAddressRequest.Lib.Model.ChangeRequestModel
#Html.DropDownListFor(model => model.UsersSystem, Model.SystemsList , new { #class = "form-control" })
Any ideas? thanks
As Stephen has mentioned you can't use the same name for the model property and the SelectList. Add a new property in ChangeRequestModel to hold the value of the selected item in the Dropdown.
public string UserSystemSelected { get; set; }
In your View
#Html.DropDownListFor(model => model.UserSystemSelected, Model.UsersSystem, new { #class = "form-control" })
Here you are populating the dropdown with Model.UsersSystem which has the list of all the SelectListItem and the VALUE SELECTED from the dropdown gets binded to UserSystemSelected.
EDIT:
You can also try this:
In your controller, inside the Action method
ViewBag.SystemList = new SelectList(
ConfigurationManager.AppSettings["UsersSystem"].ToString()
.Split(',')
.Select(x => new KeyValuePair<string, string>(x, x)),"Key", "Value");
And in your View
Html.DropDownListFor(m => m.UserSystemSelected, (SelectList)ViewBag.SystemList)
You have to pass the model into view, otherwise the model will be null in view.
Eg. first you can pass the SelectListItem list into ChangeRequestModel and then that into the view.
public ActionResult YourPage(){
return View(changeRequestModel);
}

How to assign value to dropdown for viewbag element?

I am developing MCV app with Razor syntax.
I have pass the elements to the dropdown list and I want to show selected item in that dropdown from viewbag element.
below code displays the dropdow code.
Controller Code
[SessionFilterAction]
public ViewResult Details(int id)
{
ViewBag.HODList = new SelectList(db.Employees.Where(e => e.DesignationType == "HOD"), "Id", "FullName");
ViewBag.ItemToBeSelectedInList = 5;
return View(paymentadvice);
}
View Code
if(ViewBag.DesignationTypeOfLoggedUser == "Staff")
{
#Html.DropDownList("HODList", String.Empty ,new { ???? })
}
Now I want to use viewbag element which will be select the one of the item of dropdown.
How to do this ?
ViewBag is designed to pass data from the controller to the view not to the other way.
You can use HTTP Get method for populating drop down like
[HttpGet]
public MyAction()
{
MyModel model = new MyModel();
// model.DropDwonValues is generic list class in model
model.DropDwonValues= db.Values //replace with your db table
.Select(v => new DropDownItem
{
Text = v.Name //value to go in your text field
Value = v.Id.ToString() //value to go in your ID field
})
.ToList();
return View(model);
}
Then in your view you can do:
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.DropDownId)
#Html.DropDownListFor(m => m.DropDownId , Model.DropDwonValues )
}

How to make dropdownlist show a selected value in asp.net mvc?

I have an edit page with a Html.DropDownList in it....I cant show the dropdownlist value it always shows up with Select instead i want to make the dropdown show an item as selected based on a model value say Model.Mes_Id... Any suggestion how it can be done...
<p>
<label for="MeasurementTypeId">MeasurementType:</label>
<%= Html.DropDownList("MeasurementType", // what should i give here?)%>
<%= Html.ValidationMessage("MeasurementTypeId", "*") %>
</p>
EDIT: It has the list items but i want to show a value selected in the edit view...
public ActionResult Edit(int id)
{
var mesurementTypes = consRepository.FindAllMeasurements();
ViewData["MeasurementType"] = mesurementTypes;
var material = consRepository.GetMaterial(id);
return View("Edit", material);
}
My repository method,
public IEnumerable<SelectListItem> FindAllMeasurements()
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name
};
return mesurements;
}
Set the selected item when you create the IEnumerable<SelectListItem>.
Personally I would create a specialized viewmodel for the form but going by your code, do something like:
public ActionResult Edit(int id)
{
//Put this first
var material = consRepository.GetMaterial(id);
//pass in your selected item
var mesurementTypes = consRepository.FindAllMeasurements(material.MeasurementTypeId);
ViewData["MeasurementType"] = mesurementTypes;
return View("Edit", material);
}
Then change your repository method to something like:
public IEnumerable<SelectListItem> FindAllMeasurements(int selectedId)
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name,
Selected = mt.Id == selectedId
};
return mesurements;
}
HTHs,
Charles
Have a look at this blog entry.
http://weblogs.asp.net/ashicmahtab/archive/2009/03/27/asp-net-mvc-html-dropdownlist-and-selected-value.aspx
Basically, you need to convert your mesurementTypes list/enumerable into a SelectList or IEnumerable<SelectListItem>.
I would recommend, if possible, upgrading to ASP.NET MVC2 and using Html.DropDownListFor()
You should be returning a SelectionList which can specify a selected item.
How to create a DropDownList with ASP.NET MVC
Assuming that Model.Mes_Id contais the selected value, you can do something like this
<%
var Measurements = new SelectList((IEnumerable)ViewData["MeasurementType"], "Id", "Name", Model.Mes_Id);
Response.Write(Html.DropDownList("measurement_type", Measurements, "Select"));
%>
Html.DropDownListFor didn't work for me So I got the poppy like this
(in Edit method )
CreatList(long.Parse(wc.ParentID.ToString()));
private void CreatList(long selected= 0)
{
SqlConnection conn = new SqlConnection(Config.ConnectionStringSimple);
conn.Open();
Category wn = new Category(conn);
CategoryCollection coll = new CategoryCollection();
Category.FetchList(conn, ref coll);
ViewBag.ParentID = GetList(coll, selected);
}
private List<SelectListItem> GetList(CategoryCollection coll, long selected)
{
List<SelectListItem> st = new List<SelectListItem>();
foreach (var cat in coll)
{
st.Add( new SelectListItem
{
Text = cat.Name,
Value = cat.ID.ToString(),
Selected = cat.ID == selected
});
}
SelectListItem s = new SelectListItem {
Text = Resources.lblSelect,
Value = "0"
};
st.Insert(0, s);
return st;
}
<div class="editor-label">
#Html.LabelFor(model => model.ParentID)
</div>
<div class="editor-field">
#Html.DropDownList("ddlCat", (List<SelectListItem>)ViewBag.ParentID)
#Html.ValidationMessageFor(model => model.ParentID)
</div>

Resources