Asp.Net MVC with Drop Down List, and SelectListItem Assistance - c#

I am trying to build a Dropdownlist, but battling with the Html.DropDownList rendering.
I have a class:
public class AccountTransactionView
{
public IEnumerable<SelectListItem> Accounts { get; set; }
public int SelectedAccountId { get; set; }
}
That is basically my view model for now. The list of Accounts, and a property for returning the selected item.
In my controller, I get the data ready like this:
public ActionResult AccountTransaction(AccountTransactionView model)
{
List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);
AccountTransactionView v = new AccountTransactionView
{
Accounts = (from a in accounts
select new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString(),
Selected = false
}),
};
return View(model);
}
Now the problem:
I am then trying to build the Drop down in my view:
<%=Html.DropDownList("SelectedAccountId", Model.Accounts) %>
I am getting the following error:
The ViewData item that has the key 'SelectedAccountId' is of type 'System.Int32' but must be of type 'IEnumerable'.
Why would it want me to return the whole list of items? I just want the selected value. How should I be doing this?

You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}

Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
#model MvcVariousApplication.Models.RechargeMobileViewModel
#{
ViewBag.Title = "Contact";
}
#Html.LabelFor(model=> model.CustomerFullName)
#Html.TextBoxFor(model => model.CustomerFullName)
#Html.LabelFor(model => model.MobileNumber)
#Html.TextBoxFor(model => model.MobileNumber)
#Html.LabelFor(model => model.TelecomSubscriber)
#Html.TextBoxFor(model => model.TelecomSubscriber)
#Html.LabelFor(model => model.TotalAmount)
#Html.TextBoxFor(model => model.TotalAmount)
#Html.LabelFor(model => model.Month)
#Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Related

''System.Web.Mvc.SelectListItem' does not contain a definition for 'string''

My Action method is given below:
public ActionResult Method()
{
var model = new PropertyDto();
if (!Request.Url.AbsoluteUri.Contains("?amp=1"))
{
if (DefaultCityID > 0)
model.CityID = DefaultCityID;
List<SelectListItem> Cities = cityService.GetMenuCitiesLite(1).Select(t => new SelectListItem { Text = t.Name, Value = t.ID.ToString() })
.OrderBy(o=>o.Text).ToList();
ViewBag.Cities = Cities;
ViewBag.CitiesIds = DefaultCityID;
}
ViewBag.Cities = cityService.GetMenuCitiesLite(SiteKeys.CountryID);
return View(model);
}
on the view dropdown list:
#Html.DropDownListFor(model => model.CityID, (List<SelectListItem>)ViewBag.Cities, "Select city", new RouteValueDictionary { { "data-rule-required", "true" }, { "data-msg-required", "*required" }, { "class", "form-control" }, { "id", "CityDropdown" } })
Now on the other partial view where i am getting the data of cities via viewbag is getting an exception:
#foreach (var item in ViewBag.Cities)
{
<li><a href="#(domain + item.SelfUrl)"><i class="fa fa-angle-double-
right"></i> #item.Name</a></li>
}
here i am getting the exception
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Web.Mvc.SelectListItem' does not contain a definition for 'SelfUrl''
HOW CAN I RESOLVE THIS?
SelectListItem which what item in ViewBag.Cities is, only has Text and Value and it doesn't have any of the properties you define on your models such as SelfUrl.
Simply don't use that model because you don't need it to render a list of links.
Use your own models such and initialize it like this instead of SelectListItem:
List<MyOwnModel> Cities = cityService.GetMenuCitiesLite(1).Select(t => new MyOwnModel { Text = t.Name, SelfUrl = t.ID.ToString(), Anything = "anything" })
You'll need to create the class of course:
public class MyOwnModel {
public string Text {get;set;}
public string SelfUrl {get;set;}
public string Antying {get;set;}
// put whatever you need here
}

DropdownListFor doesn't show the selected value

I am so confused how to make the dropdownlist to show the selected value.
Model:
public class SampleModel
{
public string State { get; set; }
}
Controller:
public ActionResult EditInformation()
{
ViewBag.State = new SelectList(db.States, "StateName", "StateName");
string userEmail = User.Identity.GetUserName();
Sample model = new SampleModel();
model.State = "Melbourne";
return View(model);
}
View :
#Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")
The list is showing the states just fine, but it doesn't automatically select the value I assigned ("Melbourne"). I have tried using the selectlist constructor to assign the selectedValue, but after doing a lot of research, someone wrote that it is redundant to use the selectlist constructor if you are using Html.DropdownListFor() since you will be using the value assigned to the model.
EDIT:
Here is my db.State model:
public class State
{
[Key]
public int StateId { get; set; }
public string StateName { get; set; }
}
Again to clarify, I want to use StateName as the value and the text for the selectlistitem.
EDIT:
My full action method:
public ActionResult EditInformation()
{
//var states = ndb.States.Select(s => new SelectListItem { Text = s.StateName, Value = s.StateName , Selected = s.StateName == "Jawa Timur" }).ToList();
ViewBag.State = new SelectList(ndb.States, "StateName", "StateName");
ViewBag.City = new SelectList(ndb.Cities, "CityName", "CityName");
string[] countries = { "Indonesia" };
ViewBag.Country = new SelectList(countries);
string userEmail = User.Identity.GetUserName();
try
{
UserInformation userInfo = ndb.UserInformations.Single(m => m.Email == userEmail);
UserAccountViewModel model = new UserAccountViewModel();
model.Address = userInfo.Address;
model.Email = userEmail;
model.FirstName = userInfo.FirstName;
model.LastName = userInfo.LastName;
model.Phone = userInfo.Phone;
model.PostalCode = userInfo.PostalCode;
Debug.Print(userInfo.State);
model.State = userInfo.State;
model.City = userInfo.City;
model.Country = userInfo.Country;
return View(model);
}catch { }
return View();
}
public ActionResult EditInformation(int? id /*this will be passed from your route values in your view*/)
{
State myState = db.States.Find(id)
ViewBag.State = new SelectList(ndb.States, "StateId", "StateName", myState.StateId);
}//I only added this because this is what the question pertains to.
In your EditInformation View you need to have an actionlink to link to the user's id so that you pull up the right information, so:
EditInformation View:
#foreach (var item in Model)
{
#Html.ActionLink("Edit Information", "EditInformation", /*Controller Name if this view is rendered from a different controller*/, new { id = item.id })
}
try this:
public class SampleModel
{
public int Id { get; set; }
public string State { get; set; }
}
Controller:
public ActionResult EditInformation()
{
//Select default value like this (of course if your db.States have an Id):
ViewBag.State = new SelectList(db.States, "Id", "StateName", 1 /*Default Value Id or Text*/);
. . .
return View();
}
SelectList(IEnumerable, String, String, Object) - Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, and a selected value.
View:
#Html.DropdownList("State", null, "-- Select State --")
Or Like you do:
#Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")
UPDATE:
You can get Selected text using jQuery like so:
Add #Html.HiddenFor(x => x.State)
#Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --", new { id = "stateId" })
#Html.HiddenFor(x => x.State)
JS:
$(function () {
$("form").submit(function(){
var selectedText= $("#stateId :selected").text();
$("#State").val(selTypeText);
});
});
Post:
[HttpPost]
public void UploadDocument(State model)
{
if(ModelState.IsValid)
{
string state = model.State;
}
}
OKAY, So after researching for quite some time, the problem lies in the naming convention. Apparently, you cannot use ViewBag.State for Html.DropdownListFor(m => m.State), this somehow causes the Html.DropdownListFor(m => m.State) to not reading the data properly.

Dropdownlist issue in razor

hi all i have a controller
public ActionResult Search(FormCollection collection)
{
....
var column = new Models.ColumnMapping("CTR");
ViewData["ColoumName"] = column;
var search = new Models.Search(columnname,searchvalue);
return View(search);
}
my view data contains following model property value..
public class Column {
public string ColumnName { get; set; }
public DataTypes DataType { get; set; }
}
i have to create a drop down list for ColumnName(all data contain in VIewData) and my view is like
#Html.DropDownListFor("clname", ViewData["ColoumName"] as IEnumerable<AML.Web.Models.Column>, "ColumnName", "ColumnName"))
but this is not working
Try like this, This is just an example.
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
Controller
public ActionResult CustomerInfo()
{
ViewBag.CustomerNameID = new SelectList(new[]
{
new {ID="1",Name="name1"},
new{ID="2",Name="name2"},
new{ID="3",Name="name3"},
},"ID", "Name");
return View();
}
Model
public Class ViewModel {
public int CustomerId { get; set; }
}
If you have to use #Html.DropDownListFor then it should like this #Html.DropDownListFor(m => m.CustomerId ,(List<SelectList>)ViewBag.CustomerNameID,"-- Select --", new { #class = "input-block-level" })
instead of DropDownListFor try DropDownList with SelectList().
#Html.DropDownList("clname",
new SelectList((IEnumerable) ViewData["ColoumName"], "Id", "ColoumName"))

How to populate dropdownistFor from model

I need help populating a drop down list of states in my MVC application using razor views:
In my model I have a sate property:
public SelectList State
{
get { return new SelectList(StateDictionary, "Value", "Key"); }
}
Here is a shortened version of the state dictionary
public static readonly IDictionary<string, string> StateDictionary = new
Dictionary<string, string> {
{"ALABAMA", "AL"},
{"ALASKA", "AK"},
{"AMERICAN SAMOA", "AS"},
{"ARIZONA ", "AZ"},
{"ARKANSAS", "AR"},
{"CALIFORNIA ", "CA"},
{"COLORADO ", "CO"},
{"CONNECTICUT", "CT"},
{"DELAWARE", "DE"},
{"DISTRICT OF COLUMBIA", "DC"},
{"FEDERATED STATES OF MICRONESIA", "FM"},
{"FLORIDA", "FL"},
{"GEORGIA", "GA"},
};
In my Razor view I have:
<div class="form-group">
#Html.LabelFor(m => m.State,new{#class="col-lg-2 control-label"})
#Html.DropDownListFor(m => m.State,Model.State,new {#class="form-control" })
</div>
When I try to access my view I keep getting a "Object reference not set" error
How can I populate the dropdownlist from this model?
I think you should add to your model a property
public string SelectedState { get; set; }
then in the view:
#Html.DropDownListFor(m => m.SelectedState, Model.State, new { #class="form-control" })
Then on submit you will get the selected state value on the model's SelectedState property
You need a property like this:
public string State { get; set; }
in Controller set your Dictionary in ViewBag
and in your view:
#Html.DropDownListFor(m => m.State, new SelectList(ViewBag.States, "Key", "Value"))
Try the following:
Your Model
public class YourModel
{
public string SelectedValue { get; set; }
public SelectList Values { get; set; }
}
Your Controller
public ActionResult YourMethod()
{
var dictionary = new Dictionary<string, string>
{
{"ALABAMA", "AL"},
{"ALASKA", "AK"},
{"AMERICAN SAMOA", "AS"},
{"ARIZONA ", "AZ"},
{"ARKANSAS", "AR"},
{"CALIFORNIA ", "CA"},
{"COLORADO ", "CO"},
{"CONNECTICUT", "CT"},
{"DELAWARE", "DE"},
{"DISTRICT OF COLUMBIA", "DC"},
{"FEDERATED STATES OF MICRONESIA", "FM"},
{"FLORIDA", "FL"},
{"GEORGIA", "GA"},
};
var model = new YourModel
{
// Choose one of the below options for displaying either the long or short name in the dropdown
//Values = new SelectList(dictionary, "value", "key")
Values = new SelectList(dictionary, "key", "value")
};
return View(model);
}
Your View
#model YourModel
#Html.DropDownListFor(x => x.SelectedValue, Model.Values);

How to validate DropDownListFor for values bound with list

I want to validate values in DropDownListFor but its not working. I have included required script files for client side validation too.
In ViewModel:
public class SearchViewModel
{
public List<MarriageProfile> Profiles { get; set; }
public SearchProfile SearchProfile { get; set; }
}
public class SearchProfile
{
[Required(ErrorMessage="*")]
public SelectList Ages { get; set; }
public string Age { get; set; }
}
In Controller:
var ages = AgeList
.Select(p => new SelectListItem()
{
Text = p.ToString(),
Value = p.ToString()
}).ToList();
SearchViewModel.SearchProfile.Ages = new SelectList(ages, "Text", "Value");
static List<string> AgeList = new List<string>()
{
"18-23",
"23-28",
"28-33",
"33-38",
"38-43",
"43-48"
};
In View:
#Html.DropDownListFor(model => model.Age, Model.Ages, "--Select One--", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Age)
On submitting the form, no client or server side validation is working for the dropdownlist above. What could be wrong with the code?
It appears you need to tag the Age property with the Required attribute and not the Ages list. Check out this answer: ASP.NET MVC 3 and validation attribute for dropdownlist with default value of 0

Categories