How to use multiple select in mvc 4? - asp.net

I want to use multiple select in
Chosen.
I have Skill model like,
public class Skill
{
public int Id { get; set; }
public string Name { get; set; }
}
This works in my application:
<select data-placeholder="Choose a Country..." class="chzn-select" multiple >
<option value=""></option>
<option value="United States">United States</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
</select>
I want to replace Countries data with my data. In controller i write:
var list = MyService.LoadAllSkills();
ViewBag.Skills = new MultiSelectList(list, "Id", "Name");
In view:
#Html.ListBox("Name", ViewBag.Skills as MultiSelectList,
new { #class = "chzn-select" } )
View result of #Html.ListBox() and #Html.DropDownList() is not like <select>
I get so result:
But, I want to get result as
How can I change Chosen sample?

The only difference I can see between the hardcoded example (which you stated that is working) and the one you generate with the ListBox helper is the absence of the data-placeholder attribute. So:
#Html.ListBox(
"Countries",
ViewBag.Skills as MultiSelectList,
new { #class = "chzn-select", data_placeholder = "Choose a Country..." }
)
This should at least generate the same markup as what you said is working. If it doesn't work then probably you haven't setup the plugin correctly or you have some other javascript errors. Read the documentation of the plugin about how it should be setup.

as other dudes mentioned, it seems your problem cause is not server-side (razor), it's actually client-side (most probably your Jquery plugin initialization).
probably when the plugin initialization called the html DOM is not generated yet, put your plugin initialization script at the end of the body or inside $(document).ready() and don't forget to take a look at the console to see if there is any errors
happy coding

Related

Building ASP.NET with MVC, trying to create a filter from Dropdown list

First post here so be gentle please :)
I am creating an ASP.NET with MVC web app that shows a list of items of the same class (Laptop)
I want to create a Dropdown list in the main view below each title that will allow me to filter the results OnChange - hence the selection is empty, but the user can click and select the value in the DropDown list, and the main view items list will update immediately according to the selection.
This is how the list looks now:
Snapshot of the list
I want to implement a dropdown, but I can't seem to get the selected value from the dropdown: (The DropDownlist is populated properly, and working)
<select class="form-control" asp-items="Html.GetEnumSelectList<purpose>()"
onchange="#{Model = Model.Where(m=>m.Purpose == /*HERE SHOULD BE THE VALUE SELECTED*/)}">
<option selected="selected" value="">-Select one-</option>
</select>
And then refreshing the page... but - how do I get the selected value from inside the selection?
If it was in JavaScript I would have done:
html.document.getElementById("The id of the selection").value
but I don't want JavaScript since this is all ASP.NET
To be clear, I have 5 different dropdown lists to filter by, and they can be selected or not.
You're mixing up client-side vs. server-side code. The example below uses only MVC and a full client-server architecture. Each request requires a round-trip to the server.
You have 3 components in this scenario.
ProductsViewModel.cs
public class ProductsViewModel
{
public IList<Laptop> Laptops { get; set; }
public PurposeEnum Purpose { get; set; }
}
ProductsController.cs
public class ProductsController : Controller
{
[HttpGet]
public IActionResult Index()
{
// Retrieve all records without a filter
var unfiltered = db.Laptops.ToList();
var viewModel = new ProductsViewModel() { AvailableLaptops = unfiltered };
return View(viewModel);
}
[HttpPost]
public IActionResult Index(ProductsViewModel viewModel)
{
// Use viewModel.Purpose & viewModel.Maker to filter records from database
var filtered = db.Laptops.Where(l => l.Purpose == viewModel.Purpose).ToList();
var filteredViewModel = new ProductsViewModel()
{
AvailableLaptops = filtered,
Purpose = viewModel.Purpose
};
return filteredViewModel;
}
}
Products\Index.cshtml
#model MyNameSpace.ViewModel
using (BeginForm())
{
#Html.DropDownList(Html.GetEnumSelectList<PurposeEnum>())
foreach (var l in Model.AvailableLaptops)
{
// Loop through Model.AvailableLaptops and generate table
}
<input type="submit" value="Search" />
}
When you visit the URL /Products/Index for the first time, the GET action handler will be triggered. It will generate an unfiltered list of your products along with the dropdown list required for filtering.
When you make your selection and submit the form, the POST action handler will be triggered, and use the selected values in the Purpose and Maker properties of the view model to filter the records. The same view is generated, but with a filtered down list of products.
This is very basic code that ignores validation, error handling and security.

Blazor: binding to a MultiSelectList (ideally with a checkbox)

Experimenting with Blazor (Server, if that makes any difference), and I'm having difficulty getting binding to a MultiSelectList to work....
Bit of background: I'm dealing with EF Core and have a Many-to-Many relationship, let's say between people and cars. I'm currently loading a page that shows the existing details, and allowing the user to update this page.
So in my Service, I load my Person entity from the DB, and this includes the details of all the cars they currently own. I also load the list of all the available cars. My Service method then creates a MultiSelectList and adds it to my ViewModel (to be returned to the Razor Page):
Service method
vm.CarSelector = new MultiSelectList(
allCars,
nameof(Car.CarId),
nameof(Car.Name),
person.OwnedCars.Select(oc => oc.CarId));
This is fictitious code, but I hope you get the picture. When debugging this (in the Service method) I can see that this MultiSelectList has an entry for every car, and the ones that are already selected are showing as Selected. Great!
Blazor Razor Page
So, this is where I come unstuck.... I can't work out how to do the two-way data-binding of a Razor control to this object.
I'm trying to use an <InputSelect />, but that might not be the best control to use.
ideally (actually, that's more of a "must have"), each option should have CheckBox.
I'm wondering whether the use of a MultiSelectList really buys me anything
Checkboxes are a bit different in blazor. Normally you would use the bind-value attribute on an input element as shown below, however, this is not recommended as you will only be able to read the value and NOT update the UI by changing the boolean value via code:
<input type="checkbox" #bind-value="#item.Selected"/>
Instead, use the #bind syntax for checkboxes, which is much more robust and will work both ways (changing the bound boolean value from code & interacting with the checkbox on the UI). See the syntax below:
<input type="checkbox" #bind="#item.Selected"/>
The bind attribute will automatically bind your boolean value to the "checked" property of the html element.
Also make sure you are binding to the "Selected" property rather than the "Value" property.
Using the built in bind will prevent the need to manually setup events as you did in your answer. You can also get rid of the if/else block and merge your code into a single code flow since you are now binding to the boolean rather than setting the checked property manually. If you still need to tap into an event to fire off some process(maybe hiding parts of UI on checking a box), I'd suggest using the onclick event and manually passing in the multiselect Item for each line. Here is the final code:
#foreach(var item in list)
{
<input type="checkbox" #bind="item.Selected" #onclick="(()=>handleClick(item))" />
}
#foreach(var item in list.Where(x=>x.Selected))
{
<p> Item #item.Text is Selected</p>
}
#code {
MultiSelectList list = new MultiSelectList(new List<Car> { new Car { Year = 2019, Make = "Honda", Model = "Accord" }, new Car { Make = "Honda", Model = "Civic", Year = 2019 } });
private void handleClick(SelectListItem item)
{
//Do something crazy
}
}
I got this to work with a component that takes the MultiSelectList as a parameter. There may be more elegant ways to achieve this (please do update if you know of a better way).
#using Microsoft.AspNetCore.Components
#using Microsoft.AspNetCore.Mvc.Rendering
<div class="multiselect">
<div id="checkboxes">
#foreach (var item in this.Items)
{
<div>
<label for="#item.Value">
#if (item.Selected)
{
<input type="checkbox" id="#item.Value" checked="checked" #onchange="#((e) => CheckboxChanged(e, item.Value))" />
}
else
{
<input type="checkbox" id="#item.Value" #onchange="#((e) => CheckboxChanged(e, item.Value))" />
}
#item.Text
</label>
</div>
}
</div>
</div>
#code
{
[Parameter]
public MultiSelectList Items { get; set; } = null!;
private void CheckboxChanged(ChangeEventArgs e, string key)
{
var i = this.Items.FirstOrDefault(i => i.Value == key);
if (i != null)
{
i.Selected = (bool)e.Value;
}
}
}

SelectList from Enum .NET Core

I am using the following syntax in my View to create a dropdown list from a Enum in my class. The error is
One or more compilation references are missing. Possible causes include a missing preserveCompilationContext property under buildOptions in the application's project.json.
<div class="form-group">
<select asp-for="Subscription" class="form-control" asp-items="#new SelectList(Enum.GetNames(typeof(SubscriptionTypes)))">
<option disabled selected value="">Select a Subscription</option>
</select>
</div>
The Enum in the class is:
public enum SubscriptionTypes
{
Type1, Type2, Type3
}
You should use the build in generator, to generate userfriendly Values. See [Display(Name="Some Cool Name with whitespaces"] Annotation on enum values.
Html.GetEnumSelectList<CountryEnum>()
So your razor page would look like this:
#model CountryEnumViewModel
<form asp-controller="Home" asp-action="IndexEnum" method="post">
<select asp-for="EnumCountry"
asp-items="Html.GetEnumSelectList<Some.NameSpace.CountryEnum>()">
</select>
<br /><button type="submit">Register</button>
</form>
More info here: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-2.2#the-select-tag-helper
Common root cause for this problem is using of non-fully qualified type names (like SubscriptionTypes) when no using directive is specified.
To fix it either add using directive at the source top:
#using Your.Namespace.Here
or use fully qualified type names:
<select asp-for="Subscription" class="form-control" asp-items="#new SelectList(Enum.GetNames(typeof(Your.Namespace.Here.SubscriptionTypes)))">
I think this was a pretty elegant solution. I will use one of my own examples to demonstrate. I have a Model where one of the fields needs to be selected from an enumeration. The Model is called DonationMaterials and the property is Availability
public string? Availability { get; set; } = String.Empty;
This property can have 3 values; Available, Not Available, or Unknown. I created a public static method under the model called AvailabilityOptions
public static IEnumerable<SelectListItem>? AvailabilityOptions()
{
return new[]
{
new SelectListItem { Text = "Available", Value = "Available"},
new SelectListItem { Text = "Not Available", Value = "Not Available"},
new SelectListItem { Text = "Unknown", Value = "Unknown"}
};
}
Once I created the static method, anytime I need to fill the SelectList I simply use the code in the cshtml for the page. You will need to include the Namespace of the model to have accessibility to the static method. This is clean. You could also answer the enumeration from the static method and use code to convert the enumeration into a collection of SelectListItem's
<select asp-for="DonationMaterials.Availability" asp-items="DonationMaterials.AvailabilityOptions()" class="form-control"></select>
The beauty of this approach is that the enumeration is really a Domain (mode) specific data and it keeps it where it belongs (in the model). The use of the model in the interface is quite simple.

Accessing models from view in MVC 2 Timesheet application?

I am trying to create a timesheet application in MVC 2, but I feel like I am still struggling to grasp the model/view relationships and all that.
The problem I have is, I want to let the user report a new time segment in a create view. But I want to have dropdownlists populated with Projects, Tasks, and Consultants from the model.
Basically the database structure looks like this:
(table) TimeSegments
TimeSegmentID
Hours
Date
ConsultantID (FK)
TaskID (FK)
ProjectID (FK)
(table) Projects
ProjectID
ProjectName
(table) Tasks
TaskID
TaskName
(table) Consultants
ConsultantID
ConsultantName
This design may be extended in future, right now I want to get basic functionality working before I complicate it further.
Now, I am passing the entire model to the create view (actually a viewmodel based on it, just to simplify some coding, but it might as well have been the entire model).
The problem is, normally when I have done similar things with a create view, I would have created a new object in the controller and passed that to the view. In this case it would have been the TimeSegment object, since it is a new time segment that should be created in the database. Then I could just submit it and update the database in the controller. However, if I only pass a new TimeSegment object to the view, I can't populate the dropdownlists with Projects, Tasks and Consultants.
And oppositely, if I only pass the entire model, how would I bind a textbox to a new TimeSegment to be updated in the database?
I feel like I need to send both a new TimeSegment object and the entire model to do this, but then I have no idea how I would access it (there's only that one "Model" to access from the view). Also, back in the controller after a submit, how would the controller know what to update?
I'm sure I'm just thoroughly confused still by the MVC way of thinking, but I would really appreciate it if someone could clarify this for me and tell me (as pedagogically as possible) what to do to solve this.
Okay, I will give it a shot.
MVC is not hard, but you do have to alter your way of thinking a bit. In MVC you have the Models (your data layer[s]), the Views and the Controllers.
Before we continue, I make the assumptions with my examples below that you are using LINQ to SQL for you data access layer (Model), and I have labeled it as dc.
The Controllers fetch and format the data out of the Models and hand it off to the Views to display. So lets start with your first view which would be the view to create a TimeSegment.
[HttpGet]
public ActionResult CreateTimeSegment() {
return View(new TimeSegmentView {
Consultants = dc.Consultants.ToList(),
Projects = dc.Projects.ToList(),
Tasks = dc.Tasks.ToList()
});
}
This action will create a TimeSegmentView object and pass that to the View as its Model. Keep in mind that this action is decorated with [HttpGet]. TimeSegmentView` is a container class for the objects you need to pass to the view to create your UI and it looks like this:
public class TimeSegmentView {
public IList<Consultant> Consultants { get; set; }
public IList<Project> Projects { get; set; }
public IList<Task> Tasks { get; set; }
public TimeSegment TimeSegment { get; set; }
}
NOTE: I'm not using the TimeSegment property yet, it's further down...
In the view make sure you have it inherit from TimeSegmentView. Assuming that you're following the default MVC project structure and with me taking the liberty to add a Views folder into the Models folder your full reference would look like this:
<%# Page Inherits="System.Web.Mvc.ViewPage<PROJECTNAME.Models.Views.TimeSegmentView>" %>
Now you've typed the view to that object and you can now interact with its properties. So, you can build a form such as:
<form action="/" method="post">
<p>
<label>Hours</label>
<input name="TimeSegment.Hours" />
</p>
<p>
<label>Date</label>
<input name="TimeSegment.Date" />
</p>
<p>
<label>Consultant</label>
<select name="TimeSegment.ConsultantID">
<% foreach (Consultant C in Model.Consultants) { %>
<option value="<%=C.ConsultantID%>"><%=C.ConsultantName%></option>
<% }; %>
</select>
</p>
<p>
<label>Project</label>
<select name="TimeSegment.ProjectID">
<% foreach (Project P in Model.Projects) { %>
<option value="<%=P.ProjectID%>"><%=P.ProjectName%></option>
<% }; %>
</select>
</p>
<p>
<label>Task</label>
<select name="TimeSegment.TaskID">
<% foreach (Task T in Model.Tasks) { %>
<option value="<%=T.TaskID%>"><%=T.TaskName%></option>
<% }; %>
</select>
</p>
</form>
As you can see it created 3 select fields and just performed loops in each of them to build up their values based off of the model.
Now, taking a submission of this form, we'll need to get the data and add it to our database with:
[HttpPost]
public RedirectToRouteResult CreateTimeSegment(
[Bind(Prefix = "TimeSegment", Include = "Hours,Date,ConsultantID,ProjectID,TaskID")] TimeSegment TimeSegment) {
dc.TimeSegments.InsertOnSubmit(TimeSegment);
dc.SubmitChanges();
return RedirectToAction("EditTimeSegment", new {
TimeSegmentID = TimeSegment.TimeSegmentID
});
}
Okay, first notice that I've named the action the same, but this one has an [HttpPost] decoration. I'm telling the action that I'm sending it a TimeSegment object and that I want it to bind the properties in the Include clause (this is mostly for security and validation). I then take the TimeSegment object I've passed in, add it to the data context, submit the changes and redirect. In this case I'm redirecting to another action to edit the object I just created passing in the new TimeSegmentID. You can redirect to what ever, this just felt appropriate to me...
[HttpGet]
public ActionResult EditTimeSegment(
int TimeSegmentID) {
return View(new TimeSegmentView {
Consultants = dc.Consultants.ToList(),
Projects = dc.Projects.ToList(),
Tasks = dc.Tasks.ToList(),
TimeSegment = dc.TimeSegments.Single(t => t.TimeSegmentID == TimeSegmentID)
});
}
In the edit action your doing the same thing as in the create action by building a new TimeSegmentView object and passing it to the view. The key difference here is that you're now populating the TimeSegment property. Your form would look something like this (shortened from above):
<form action="/<%=Model.TimeSegment.TimeSegmentID%>" method="post">
<p>
<label>Hours</label>
<input name="TimeSegment.Hours" value="<%=Model.TimeSegment.Hours%>" />
</p>
</form>
And your receiving action on the controller would look like this:
[HttpPost]
public RedirectToRouteResult EditTimeSegment(
int TimeSegmentID) {
TimeSegment TS = dc.TimeSegments.Single(t => t.TimeSegmentID == TimeSegmentID);
TryUpdateModel<TimeSegment>(TS, "TimeSegment", new string[5] {
"Hours", "Date", "ConsultantID", "ProjectID", "TaskID"
});
dc.SubmitChanges();
return RedirectToAction("EditTimeSegment", new {
TimeSegmentID = TimeSegment.TimeSegmentID
});
}
Lastly, if you want to display a list of TimeSegments you can do something like this:
[HttpGet]
public ActionResult ListTimeSegments() {
return View(new TimeSegmentsView {
TimeSegments = dc.TimeSegments.ToList()
});
}
And TimeSegmentsView looks like this:
public class TimeSegmentsView {
public IList<TimeSegment> TimeSegments { get; set; }
}
And in the View you'd want to do this:
<table>
<% foreach (TimeSegment TS in Model.TimeSegments) { %>
<tr>
<td><%=TS.Hours%></td>
<td><%=TS.Date%></td>
<td><%=TS.Project.ProjectName%></td>
<td><%=TS.Consultant.ConsultantName%></td>
<td><%=TS.Task.TaskName%></td>
</tr>
<% }; %>
</table>
I hope this is enough to give you a start. It's by no means complete, but its 5 AM and I haven't slept yet, so this will have to do for now (from me). Feel free to name your actions what you want, you don't have to stick to my naming conventions.
I would suggest however that you change the naming of the properties of your tables. For example when your writing the expressions like in the table above you'll have to do TS.Project.ProjectName and that's redundant. You're already accessing the Project property of TS through their relationship so you know you're only going to work with a Project. This then makes ProjectName a pointless blob of text re-describing the object your working with. Instead just use Name, and turn your expression to TS.Project.Name.
Anyway, just a suggestion, do what you like better. I'm passing out, so good night and happy Thanksgiving!
UPDATE
The process with collections is essentially the same as far as the controller side is conserned. It's the client side and the JavaScript that's more difficult to get going, so I'll assume that you have something established on that end.
So, here's how the controller would work. You pass in an array of TimeSegment and the model binder is smart enough to figure it out through the Prefix of your form elements.
<form action="/<%=Model.TimeSegment.TimeSegmentID%>" method="post">
<p>
<label>Hours</label>
<input name="TimeSegment[0].Hours" />
<!-- Notice the array in the prefix -->
</p>
<p>
<label>Hours</label>
<input name="TimeSegment[1].Hours" />
<!-- Notice the array in the prefix -->
</p>
</form>
And the controller:
[HttpPost]
public RedirectToRouteResult CreateTimeSegments(
[Bind(Prefix = "TimeSegment", Include = "Hours,Date,ConsultantID,ProjectID,TaskID")] TimeSegment[] TimeSegments) {
dc.TimeSegments.InsertAllOnSubmit(TimeSegments);
dc.SubmitChanges();
return RedirectToAction("ListTimeSegments");
}
And that's it. Of course you'll want to validate or do other stuff before sending to the database, but that's roughly all there is to it.
UPDATE 2
I believe you can do an IList<TimeSegment> instead of TimeSegment[] without issues, but as far as if it's better, that's up for debate. The way I look at it the browser still sends a virtual array to the server so having the action receive an array feels natural, but its up to you what you want to use.
So, a generic list action would look like this:
[HttpPost]
public RedirectToRouteResult CreateTimeSegments(
[Bind(Prefix = "TimeSegment", Include = "Hours,Date,ConsultantID,ProjectID,TaskID")] IList<TimeSegment> TimeSegments) {
dc.TimeSegments.InsertAllOnSubmit(TimeSegments);
dc.SubmitChanges();
return RedirectToAction("ListTimeSegments");
}
Keep in mind that I haven't used this (meaning the IList) before so I can't guarantee it will work, just speculating...
UPDATE 3
About what you want to do with the Consultant, it sound a lot like what I do with Cookies. I have a BaseView class which is the type used by the Site.Master and then all other views extend from it. In the BaseView I have a Cookie property which is always populated by each controller action. I then use that property to get the id of the currently authorized user.
So, in code it looks like this (using examples from one of my apps):
public class BaseView {
// Don't confuse with an HttpCookie, this is an object in my database...
public Cookie Cookie { get; set;}
}
public class EmployeeView : BaseView {
public Employee Employee { get; set; }
}
And with this, say I want to add a note to an employee, my form would look like this where I pass in a hidden field which is where your ConsultantID comes into play.
<form>
<input type="hidden" name="Note.AuthorId" value="<%=Model.Cookie.EmployeeId%>" />
<!-- other fields -->
</form>
Hope this helps.

ASP.NET MVC 2 - Select List Item without Database

I am still struggling with this--
All I am after is an order form, initially it will be a laptop order form but it might be a computer, printer etc in the future. So I have an Order Controller with a Laptop Action which makes a new laptop model. In the model I want to collect various information such as Customer Name, Customer Details etc. In my MODEL I also want to keep a Select List but I've been trying for ages and just cant seem to get it running. My laptop model has this:
--Laptop Model Select List
public SelectList screenSize = new SelectList(new[]
{
new SelectListItem { Text = "11.6", Value = "11.6" },
new SelectListItem { Text = "15.6", Value = "15.6" },
new SelectListItem { Text = "17", Value = "17" }
}, "Value", "Text");
In the controller I accept the laptop on the post
[HttpPost]
public ActionResult Index(Laptop laptopToEmail)
{
if (ModelState.IsValid)
{
...send an email
}
else return View(laptopToEmail)
}
In the view i am able to render out the list of items and I have a select list but I dont get a value passed to the email when i use
laptopToEmail.screenSize.SelectedValue
The view has this helper.
<%: Html.DropDownList("screenSize",Model.screenSize) %>
Am i missing something here? Surely it cant be this difficult to get a select list to work without a database in MVC.
You know, all these neato MVC Html helpers do have HTML equivalents. For a 2-item drop down, why not just write a bit of html:
<select>
<option value="a">Option A</option>
<option value="b">Option b</option>
</select>

Resources