I am trying to create a multiple select from a single select drop down menu.
my model originally had:
public int country_id { get; set; }
and my view had:
#Html.DropDownList("country_id", String.Empty)
to change it to multiple select i changed my model to:
public List<Country> country_id { get; set; }
and my view to:
#Html.ListBoxFor(model => model.country_id, ViewBag.ActionsList as MultiSelectList, new { #class = "multiselect", #style = "width: 450px;height:200px" })
the problem i am having is updating my databse using migration since the i am changing int to list, however, it keeps saying
"Cannot drop the index 'dbo.People.IX_country_id', because it does
not exist or you do not have permission."
I do have permission so I am not sure if I am missing something?
My list of countries is coming straight from the country database.
thanks for your inputs.
You need to populate a selectlist in the controller & pass it to the view, something like this:
var countries = from d in db.Countries
select new
{
Id = d.Id,
Name = d.Name
};
// I'd pass this in a model, but use ViewBag if that's what you're familiar with
ViewBag.ActionsList = new SelectList(countries , "Id", "Name");
And in the View:
#Html.DropDownListFor(model => model.country_id, ViewBag.ActionsList)
UPDATE:
You should use a ViewModel for this:
public class CountryList
{
// this may have to be a List<SelectListItems> to work with MultiSelectList - check.
public SelectList Countries{ get; set; }
public List<int> SelectedCountryIds { get; set; }
}
In the controller:
var model = new CountryList
{
SelectList = //assign the selectlist created earlier
}
return View(model);
In the View:
#Html.ListBoxFor(m => m.SelectedCountryIds, new MultiSelectList(#Model.Countries, "Id", "Name", #Model.SelectedCountryIds))
Related
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.
I am new to MVC and EF, but i have a group of models that represent lookup tables that all have the same structure
public int ID {get; set;}
public string Value {get; set;}
public bool IsActive {get; set;}
Rather than writing one Controller and View for each is there a way to create one, that is defined by a previous selected value.
So if 2 of my lookups are Gender and Status and a dropdown with these values
can I then take the name of the selected option and then dynamically bind to the model
so rather than having Status status = new Status its Object object = new Object where object has been defined by the selection of Status in the previous dropdown
It is definitely possible. There are several ways you could achieve this. You could have an EditorTemplate with everything you need to display your dropdown. In ~/Views/Shared/EditorTemplates/DropDown.cshtml
#model string
#{
Layout = null;
List<SelectListItem> ListItems = (List<SelectListItem>)ViewBag.ListItems;
}
// not sure what the syntax for a dropdown is, I don't use them
#Html.SelectFor(m => Model, ListItems)
Then in your view
#Html.EditorFor(m => m.Status, "DropDown", new { ListItems = MyModel.StatusSelectListItems })
#Html.EditorFor(m => m.Gender, "DropDown", new { ListItems = MyModel.GenderSelectListItems })
Where in your model you would have the selection options:
public class MyModel
{
// other stuff
public static List<SelectListItem> GenderSelectListItems = new List<SelectListItem>
{
new SelectListItem{ Value = "Male", Text = "Male" },
new SelectListItem{ Value = "Female", Text = "Female" }
};
// etc
}
I have a table with Category Id and Parent Category Id.
Category Id Category Name Parent Category Id
1 Desktop 0
2 PC 1
3 Mac 1
How do I return it in a dropdownlist in the below format:
hi buddy i looked for this much and i couldn't find it but finally i coded it myself.
i will try to tell you how i solved this problem and works great just like ur screenshot. here is my secreenshot
here is my category model it is almost same with ur model
public class Category
{
public int ID { get; set; }
public string CategoryName { get; set; }
public int? ParentID { get; set; }
[ForeignKey("ParentID")]
public virtual ICollection<Category> SubCategories { get; set; }
}
then i created a View category model like this
public class ViewModelCategory
{
public Category Category { get; set; }
public List<SelectListItem> Categories { get; set; }
public List<SelectListItem> ChildCategories { get; set; }
public List<SelectListItem> AllCategories
{
get
{
List<SelectListItem> sli = new List<SelectListItem>();
foreach (SelectListItem item in Categories)
{
sli.Add(item);
}
foreach (SelectListItem item in ChildCategories)
{
int i = item.Text.IndexOf(">");
string text = item.Text.Substring(0, i-1);
foreach (SelectListItem listItem in ChildCategories)
{
int k = listItem.Text.LastIndexOf(">");
string text2 = listItem.Text.Substring(k+1);
if (text2.Contains(text))
{
item.Text = listItem.Text + " > " + item.Text.Substring(i+2);
}
}
sli.Add(item);
}
return sli;
}
}
}
my codes can look like little complicate but is is not actually.
there are something important in my ViewModelCategory model when u look at the model u will see 3 selectlistitem properties. i wanna talk about these first.
i created one of them called as "Categories" for main categories that has no any parent id value.
second of them called as "ChildCategories" contains only subcategories that has parent id value
when u look at he controller codes u will see already.
and the last one of called as "AllCategories". this one is the important one couse i merged all categories in this property to send categories to dropdownlisfor in controller's view. but it is not just for this i also did something important in this property while i merged them when u look at the loops u will see it. i used loops to place categories to their parents
then used my ViewModelCategory model in controller like this
ViewModelCategory vmc = new ViewModelCategory
{
Category = category,
Categories = _businessCategories.GetItems().Where(x => x.ParentID == null).Select(x => new SelectListItem
{
Text = x.CategoryName,
Value = x.ID.ToString()
}).ToList(),
ChildCategories = _businessCategories.GetItems().Where(x=>x.ParentID != null).Select(x => new SelectListItem
{
Text = _businessCategories.GetItems().Where(a => a.ID == x.ParentID).FirstOrDefault().CategoryName + " > " + x.CategoryName,
Value = x.ID.ToString()
}).ToList(),
};
and finally i welcomed my datas from view like this
<div class="form-group">
<label class="col-sm-4 control-label">Sub Category</label>
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Category.ParentID, Model.AllCategories.OrderBy(x=>x.Text), "Select Category", new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.Category.ParentID)
</div>
</div>
hope u will like this have a nice day
The best thing I can think of would be to create some class that hold the Name and Value for a drop down list and use it to create a SelectList in your Action.
public class SelectListValue{
public string Text {get;set;}
public string Value {get;set;}
}
public ActionResult SomeActionMethod()
{
var categories = GetCategories() //Get your list of categories
var selectListItems = new List<SelectListValue>();
foreach(var item in categories)
{
var text = GetCategoryDisplay() //You will need to figure out how to generate the text, like Components > Web Cameras. This doesn't need to be a method. It could be a property on the Category object.
selectListItems.Add(new SelectListValue {Text = text, Value = item.CategoryId.ToString()});
}
ViewData["CategoryList"] = new SelectList(selectListItems, "Value", "Text");
}
You will need to have a way somewhere, probably in your model, to take generate the name string. I am guessing you are already doing that. Then in your view you would do something like
#Html.DropDownListFor(x => x.CategoryId, ViewData["CategoryList"] as SelectList)
This should work, or at least something like it.
I would like to create a simple drop-down box that displays a list of countries. The data for it comes from the database and is accessed using the entity framework data context. The user should select a country before posting the data back.(simple validation check).
I've created the view model and have also written some code, but I'm not sure about my design and I also need help to complete the code. I've done some search, but I couldn't find a simple way of doing this. I'm still getting the data from context because I am still not sure about how to use repositories. At the moment, I just want the basic drop-down to work without getting too advanced. Please help. Thanks
Updated
View Model - Country.cs
public class Country
{ [Required]
public int Id { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
Controller
Public ActionResult CountriesDropDown()
{
Models.Country countryModel = new Models.Country();
using (ctx)
{
var model = (from q in ctx.Countries
select new SelectListItem
{
Text = q.CountryId,
Value = q.CountryName
}).ToList();
countryModel.Countries = model;
}
return View("Test",countryModel);
}
Countries View
#using (Html.BeginForm("DoSomething", "Test", FormMethod.Post))
{
#Html.DropDownListFor(model => model.Id, Model.Countries, "Please Select")
#Html.ValidationMessageFor(model => model.Id) //The validation part still Not Working. I want the user to select a country before submitting the form. Please help
<input type = submit value="submit" />
}
[HttpPost]
public ActionResult DoSomething(Models.Country Selectedcountry)
//country.Id holds the value of selected drop-down and it works fine
{
if (ModelState.IsValid)
//I need to do server-side validation and return back to client if Selectedcountry.Id is null (just in case, the client-side validation doesn't work)
{
return View();
}
else
{
return View("Test");
}
}
Thanks
Do this in your controller:
var model = new Country {
// assuming that the country with "id" exists
CountryId = ctx.Countries.Get(id).Id
};
model.Countries =
from q in ctx.Countries
select new SelectListItem {
Text = q.Id,
Value = q.Name
};
return view("countries", model);
Do this in your model
#model Models.Country
#Html.DropDownListFor(model => model.CountryId, model.Countries)
try this:
[Required(ErrorMessage = "Please select a Country")]
public string CountryCode{ get; set; }
public IEnumerable<SelectListItem> CountryList
{
get
{
return Country
.GetAllCountry()
.Select(Country=> new SelectListItem
{
Text = Country.Value,
Value = Country.Value
})
.ToList();
}
}
and then you could add a corresponding validation error message:
#Html.DropDownListFor(model => model.CountryCode, Model.CountryList, "select")
#Html.ValidationMessageFor(model => model.CountryCode)
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-")