Asp.Net Mvc Selectpicker - c#

I am trying to implement a DropDownList Multi Select using Bootstrap Selectpicker for selecting Schools in my application.
I am not very familiar with MVC and JQuery since i have been using webforms for a long time, so i am learning from internet to accomplish.
Here is the scenario:
on my layout, there is a DropDownList:
#*DropDownList Select School*#
#Html.DropDownList("Schools", null, null, new { id = "MultiSelect", #class = "selectpicker form-control", multiple = "", title = "School" })
The code to fill the DropDownList:
public ActionResult Class()
{
IEnumerable<SelectListItem> ListClasses = db.scasy_class
.OrderBy(a => a.class_name)
.Select(c => new SelectListItem
{
Value = c.id.ToString(),
Text = c.class_name,
Selected = false
});
ViewBag.Class = ListClasses.ToList();
ClassViewModel classViewModel = new ClassViewModel()
{
SelectOptions = ListClasses
};
return View(classViewModel);
}
On layout, when the user selects some schools, using the dropdownlist,
$('#MultiSelect').on('change', function () {
$.each($("#MultiSelect option"), function () {
$.post("/Setup/Student/SetSchool/", { school: $(this).val(), selected: $(this).prop('selected') });
});
});
and the controller;
public ActionResult SetSchool(int school, bool selected)
{
ArrayList school_nos = Session["Schools"] as ArrayList;
if (selected)
{
if (!school_nos.Contains(school))
{
school_nos.Add(school);
}
}
else
{
if (school_nos.Contains(school))
{
school_nos.Remove(school);
}
}
Session["Schools"] = school_nos;
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
it is working as it is expected until here.
For the next reload, i am trying to fill the dropdownlist with the same data but show previously selected schools with tick, using Session values, since i will need this information on many other pages.
$(document).ready(function () {
$.getJSON("/Setup/Student/GetSchool/",
function (data) {
var myData = [];
$.each(data, function (index, item) {
if (item.Selected == true) {
myData.push(item.Value);
}
});
//alert(myData);
$('#MultiSelect').selectpicker('val', myData);
});
});
and the controller;
public JsonResult GetSchool()
{
IEnumerable<SelectListItem> ListSchools = db.scasy_school
.OrderBy(a => a.name)
.Select(a => new SelectListItem { Value = a.id.ToString(), Text = a.name});
ArrayList school_nos = Session["Schools"] as ArrayList;
List<SelectListItem> ListSchoolsUpdated = new List<SelectListItem>();
foreach (var item in ListSchools)
{
SelectListItem selListItem;
if (school_nos.Contains(item.Value.ToString()))
{
selListItem = new SelectListItem() { Value = item.Value.ToString(), Text = item.Text, Selected = true };
}
else
{
selListItem = new SelectListItem() { Value = item.Value.ToString(), Text = item.Text, Selected = false };
}
ListSchoolsUpdated.Add(selListItem);
}
return Json(ListSchoolsUpdated, JsonRequestBehavior.AllowGet);
}
Code throws no error, but i cannot have the dropdownlist with selected items shown.

Declare a model class for your page
public class ClassViewModel {
public List<int> SelectedSchools {get; set;}
public List<SelectListItem> Schools {get; set;}
}
Set Selected Schools in your controller action.
Set Your View Model
#model ClassViewModel
Then in your view use this code to show dropdownlist
#Html.ListBoxFor(m=> m.SelectedSchools , Model.Schools, new {id = "MultiSelect", #class = "selectpicker form-control", title = "School" })

Related

List<SelectListItem> Selected Value Not Showing for #Html.DropDownListFor

I have a razor page. On load it goes through the below function and creates a list of SelectListItem:
List<SelectListItem> groups = new List<SelectListItem>();
for (int i = 0; i < Model.List.key.Count(); i++)
{
bool selected = false;
if(Model.List.key[i] == Model.rkey)
{
selected = true;
}
groups.Add(new SelectListItem
{
Text = Model.List.description[i],
Value = Model.List.key[i].ToString(),
Selected = selected
});
}
It is properly setting the Selected value to true when the keys match, however it is not displaying the selected value:
#Html.DropDownListFor(model => Model.groupTypeList, groups, new { #class = "form-control", onchange = "chosenGroup(this.value)", id = "groupTypeList" })
The above ddl shows all the values that were added, but does not get set to the Selected value. I tried the below but it then show the selected value twice:
#Html.DropDownListFor(model => Model.groupTypeList, groups, groups.First(x => x.Selected == true).Text, new { #class = "form-control", onchange = "chosenGroup(this.value)", id = "groupTypeList" })
You can try this:
Model:
public class Group
{
public IEnumerable<Key> List { get; set; }
public int rkey { get; set; }
}
public class Key
{
public int key { get; set; }
public string desc { get; set; }
}
Action Controller:
public ActionResult Index()
{
Group g = new Group
{
List = new List<Key>()
{
new Key { key = 1, desc = "Test" } ,
new Key { key = 2, desc = "Test2" },
new Key { key = 3, desc = "Test3" },
new Key { key = 4, desc = "Test4" },
new Key { key = 5, desc = "Test5" }
}
};
g.rkey = 4;
return View(g);
}
View:
#model WebMVC.Models.Group
<div>
#{
List<SelectListItem> groups = new List<SelectListItem>();
for (int i = 0; i < Model.List.Count(); i++)
{
bool selected = false;
if (Model.List.ElementAt(i).key == Model.rkey)
{
selected = true;
}
groups.Add(new SelectListItem { Text = Model.List.ElementAt(i).desc, Value = Model.List.ElementAt(i).key.ToString(), Selected = selected });
}
}
<label>Select option:</label>
#Html.DropDownList("MyDropDownList", groups, null, new { #class = "form-control", onchange = "chosenGroup(this.value)", id = "groupTypeList" })
</div>
Another way is using DropdownListFor directly without the razor validation in the view:
#Html.DropDownListFor(x => x.rkey, new SelectList(Model.List, "key", "desc"), null, new { #class = "form-control", onchange = "chosenGroup(this.value)", id = "groupTypeList" })

asp.net mvc Html.DropDownListFor: how to handle selected id

I have a problem with using #Html.DropDownListFor element.
What i have:
Model 'DatabaseModel':
public class DirectionEntity
{
public string Id { get; set; }
public string DirectionName { get; set; }
}
public class ViewModel
{
public int SelectedDirectionID { get; set; }
public List<DirectionEntity> DirectionList { get; set; }
}
Model 'DataFactory':
public class DataFactory
{
public static ViewModel Refresh()
{
using (var db = new MyDatabase())
{
return new ViewModel()
{
DirectionList = db.Directions.Select(_ => new { _.Id, _.DirectionName })
.ToList()
.Select(_ => new DirectionEntity() { Id = _.Id.ToString(), DirectionName = _.DirectionName })
.ToList(),
};
}
}
}
Controller:
public System.Web.Mvc.ActionResult AddNewDocument()
{
var db = DataFactory.Refresh();
return View(db);
}
[HttpPost]
public System.Web.Mvc.ActionResult AddNewEntry(ViewModel m)
{
m = DataFactory.Save(m);
ModelState.Clear();
return View(<some view>);
}
View:
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedDirectionID, new SelectList(Model.DirectionList.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.DirectionName }), "Value", "Text"), new { #class = "Duration", required = "required" })
<button type="submit" class="btn btn-default SaveAll">Save</button>
}
The question:
How to handle 'SelectedDirectionID' value, after user selected some position on dropdownlist, but not yet sent the request to the server using a POST-method.
See what the id of your dropdown is and then you can subscribe to the change event on the client side. You can do this using jQuery.
$("#idOfYourDropDown").change(function () {
// Do whatever you need to do here
// Here are some ways you can get certain things
var end = this.value;
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
});
Also you should see my answer here on why you should not return a view from a POST action the way you are.
In this case you have to use Jquery. As per your view id for your drop down is 'SelectedDirectionID';
Your Js:
$(document).ready(function () {
var selectedValue = $('#SelectedDirectionID').val();
var selectedText = $("#SelectedDirectionID option:selected").text();
});
Or Inside drop down change event.
$('#SelectedDirectionID').change(function () {
var selectedValue = $(this).val();
var selectedText = $(this).find("option:selected").text();
});

MVC dropdownlist required field validation not working

I am new to MVC, as part of my work i need to validate drop down list with required field validation, i tried in below way but Validation not working,
When i click on submit button without selecting a dropdown menu Validation is not working.
Model:
[Required(ErrorMessage = "*Required")]
[Display(Name = "Environment")]
public int? Environment { set; get; }
Controller:
List<SelectListItem> environmentlist = new List<SelectListItem>();
environmentlist.Add(new SelectListItem { Text = "SIT", Value = "1" });
environmentlist.Add(new SelectListItem { Text = "UAT", Value = "2" });
environmentlist.Add(new SelectListItem { Text = "PROD", Value = "3" });
ViewBag.EnvironmentList = environmentlist;
View:
#Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, String.Empty)
#Html.ValidationMessageFor(model => model.Environment)
This can be help in your code,
Public ActionResult yourMethod()
{
if (ModelState.IsValid)
{
// Your code
}
else
{
return View("Same View");
}
}
Learn more about ModelState.IsValid.
Try the following
#Html.DropDownListFor(model => model.Environment,(IEnumerable<SelectListItem>)ViewBag.EnvironmentList, new {required = "required"})

Defining a select list through controller and view model

I have a View Model that looks like this:
public class SomeViewModel
{
public SomeViewModel(IEnumerable<SelectListItem> orderTemplatesListItems)
{
OrderTemplateListItems = orderTemplatesListItems;
}
public IEnumerable<SelectListItem> OrderTemplateListItems { get; set; }
}
I then have an Action in my Controller that does this:
public ActionResult Index()
{
var items = _repository.GetTemplates();
var selectList = items.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }).ToList();
var viewModel = new SomeViewModel
{
OrderTemplateListItems = selectList
};
return View(viewModel);
}
Lastly my view:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template")
The code works fine and my select list populates wonderfully. Next thing I need to do is set the selected value that will come from a Session["orderTemplateId"] which is set when the user selects a particular option from the list.
Now after looking online the fourth parameter should allow me to set a selected value, so if I do this:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text", 56), "Please select an order template")
56 is the Id of the item that I want selected, but to no avail. I then thought why not do it in the Controller?
As a final attempt I tried building up my select list items in my Controller and then passing the items into the View:
public ActionResult Index()
{
var items = _repository.GetTemplates();
var orderTemplatesList = new List<SelectListItem>();
foreach (var item in items)
{
if (Session["orderTemplateId"] != null)
{
if (item.Id.ToString() == Session["orderTemplateId"].ToString())
{
orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = true });
}
else
{
orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() });
}
}
else
{
orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() });
}
}
var viewModel = new SomeViewModel
{
OrderTemplateListItems = orderTemplatesList
};
return View(viewModel);
}
Leaving my View like so:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template")
Nothing!
Why isn't this working for me?
You say "56 is the Id of the item that I want selected, but to no avail"
Should the fourth parameter you refer to be a string, not an integer, like so:
#Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text", "56"), "Please select an order template")

Getting Multiple Selected Values in Html.DropDownlistFor

#Html.DropDownListFor(m => m.branch, CommonMethod.getBranch("",Model.branch), "--Select--", new { #multiple = "multiple" })
#Html.DropDownListFor(m => m.division, CommonMethod.getDivision(Model.branch,Model.division), "--Select--", new { #multiple = "multiple" })
I have two instances of DropDownListFor. I want to set selected as true for those which have previously stored values for Model.branch and Model.division. These are string arrays of stored ids
class CommonMethod
{
public static List<SelectListItem> getDivision(string [] branchid , string [] selected)
{
DBEntities db = new DBEntities();
List<SelectListItem> division = new List<SelectListItem>();
foreach (var b in branchid)
{
var bid = Convert.ToByte(b);
var div = (from d in db.Divisions where d.BranchID == bid select d).ToList();
foreach (var d in div)
{
division.Add(new SelectListItem { Selected = selected.Contains(d.DivisionID.ToString()), Text = d.Description, Value = d.DivisionID.ToString() });
}
}
}
return division;
}
}
The returned value of division is selected as true for the selected item in the model, but on view side it is not selected.
Use a ListBoxFor instead of DropDownListFor:
#Html.ListBoxFor(m => m.branch, CommonMethod.getBranch("", Model.branch), "--Select--")
#Html.ListBoxFor(m => m.division, CommonMethod.getDivision(Model.branch, Model.division), "--Select--")
The branch and division properties must obviously be collections that will contain the selected values.
And a full example of the proper way to build a multiple select dropdown using a view model:
public class MyViewModel
{
public int[] SelectedValues { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
that would be populated in the controller:
public ActionResult Index()
{
var model = new MyViewModel();
// preselect items with values 2 and 4
model.SelectedValues = new[] { 2, 4 };
// the list of available values
model.Values = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
new SelectListItem { Value = "4", Text = "item 4" },
};
return View(model);
}
and in the view:
#model MyViewModel
...
#Html.ListBoxFor(x => x.SelectedValues, Model.Values)
It is the HTML helper that will automatically preselect the items whose values match those of the SelectedValues property.
For me it works also for #Html.DropDownListFor:
Model:
public class MyViewModel
{
public int[] SelectedValues { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
Controller:
public ActionResult Index()
{
var model = new MyViewModel();
// the list of available values
model.Values = new[]
{
new SelectListItem { Value = "2", Text = "2", Selected = true },
new SelectListItem { Value = "3", Text = "3", Selected = true },
new SelectListItem { Value = "6", Text = "6", Selected = true }
};
return View(model);
}
Razor:
#Html.DropDownListFor(m => m.SelectedValues, Model.Values, new { multiple = "true" })
Submitted SelectedValues in controller looks like:
Though quite old thread but posting this answer after following other answers here, which unfortunately didn't work for me. So, for those who might have stumbled here recently or in near future, Below is what has worked for me.
This is what helped me
The catch for me was MultiSelectList class and I was using SelectList.
Don't know situation in 2012 or 2015. but, now both these helper methods #Html.DropDownListFor and #Html.ListBoxFor helper methods accept IEnumerable<SelectListItem> so you can not pass any random IEnumerable object and expect these helper methods to do the job.
These helper methods now also accept the object of SelectList and MultiSelectList classes in which you can pass the selected values directly while creating there objects.
For example see below code how i created my multi select drop down list.
#Html.DropDownListFor(model => #Model.arrSelectUsers, new MultiSelectList(Model.ListofUsersDTO, "Value", "Text", #Model.arrSelectUsers),
new
{
id = "_ddlUserList",
#class = "form-control multiselect-dropdown",
multiple = "true",
data_placeholder = "Select Users"
})

Categories

Resources