ASP.NET Razor page dropdown list - c#

<div class="form-group">
#Html.LabelFor(model => model.CountyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CountyId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CountyId, "", new { #class = "text-danger" })
</div>
</div>
So I have the following code on my website. What I want to do is instead of having a text field where you type the countyID I would like to have the county name dropdown list where the user selects it by name and it would still register as a number. (For example instead of writing "1" he would just click and choose County1 from a list I make)
Edit:
Alright now I have this code
#Html.DropDownList("Counties", new List<SelectListItem>
{
new SelectListItem {Text = "Alba", Value = "1", Selected = true },
new SelectListItem {Text = "Arad", Value = "2" },
new SelectListItem {Text = "Arges", Value = "3" },
new SelectListItem {Text = "Bacau", Value = "4" },
}, "Select County")
#Html.EditorFor(model => model.CountyId, new { htmlAttributes = new { #class = "form-control" } })
How do I write it to replace the #Html.EditorFor(model => model.CountyId with the DropDownList selection?
Edit2: how do I use #Html.DropDownListFor ?

Buda, please try below
<div class="form-group">
#Html.LabelFor(model => model.CountyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountyId, new List<SelectListItem>
{
new SelectListItem {Text = "Alba", Value = "1", Selected = true },
new SelectListItem {Text = "Arad", Value = "2" },
new SelectListItem {Text = "Arges", Value = "3" },
new SelectListItem {Text = "Bacau", Value = "4" },
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountyId, "", new { #class = "text-danger" })
</div>
</div>

You can use the Html.DropDownListFor helper method
Add a new property to your view model to store the dropdown options. This property should be of type List
public class CreateUser
{
public int CountryId {set;get;}
public List<SelectListItem> Countries {set;get;}
}
Now in your GET action, populate the Countries collection property value on this view model object.
public ActionResult Create()
{
var vm = new CreateUser();
vm.Countries = new List<SelectListItem> {
new SelectListItem { Value="1", Text="USA" },
new SelectListItem { Value="2", Text="Canada" },
new SelectListItem { Value="3", Text="Mexico" }
};
return View(Vm);
}
And in your view
#model CreateUser
#using(Html.BeginForm())
{
<label>Select country</label>
#Html.DropDownListFor(s=>s.CountryId,Model.Countries,"Select one")
<input type="submit" />
}

Buda,
Probably you need to use the DropDownListFor html helper.
Please check the following answer to see if it clarifies your question
ASP.NET MVC + Populate dropdownlist

There are so many ways to do this, you can use this :
<div class="form-group col-4">
<label for="issueinput6">category</label>
<select id="issueinput6" class="form-control" data-toggle="tooltip" data-trigger="hover" data-placement="top"
data-title="Status">
#foreach (var item in ViewData["Categoryes"] as IList<AirPortModel.Models.Category>)
{
<option value="#item.Id">#item.CategoryName</option>
}
</select>
</div>
This way, you have all the information you want as a drop down.
These codes are from my project but you can change the names to use it for your own.
Also, you can use this pic of code to solve your problem.
<select data-val="true" data-val-required="The Category field is required." id="category" name="1">
<option value="">Pick one</option>
<option selected="selected" value="0">blabla</option>
<option value="1">blabla</option>
<option value="2">blabla</option>
<option value="3">blabla</option>
<option value="4">blabla</option>
<option value="5">blabla</option>
<option value="6">blabla</option>

Related

Set selected drop down value from database in razor view MVC

I am explicitly creating a dropdownlist in razor mvc view. I would like the default option to be one of the items, the value of that item should come from database
View Code
<div class="form-group">
#Html.LabelFor(model => model[i].Customer.HomeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
#Html.DropDownListFor(model => model[i].Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House",#(Model[i].CustomerServices.HomeType == "House" ? Selected = true : false) },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { #class = "form-control" })
}
</div>
</div>
Controller Code
cs.HomeType = serviceDetails.HomeType;
sp.CustomerServices = cs;
return View("EditCustomerServices", ProviderList);
Model has the data I need but how can I set it to correct Dropdown list value. I tried using short hand if but it gives me an error
Invalid member initializer
Can I add if condition for Selected Boolean?
#{
var selected = Model.CustomerServices.HomeType == "House";
}
<div class="form-group">
#Html.LabelFor(model => model.Customer.HomeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="SerivcesRegistrationInput col-md-10">
#Html.DropDownListFor(model => model.Customer.HomeType, new List<SelectListItem>
{
new SelectListItem{ Text="House", Value = "House", Selected = selected },
new SelectListItem{ Text="Apartment", Value = "Apartment" },
new SelectListItem{ Text="Farm", Value = "Farm" } },
"Select your home type", htmlAttributes: new { #class = "form-control" })
}
</div>
</div>

Create function not saving data to database

I'm trying to get the create function to have the user selected values entered into the database. When the create button is pushed, no error is thrown but, the data is not populated. I'm pretty sure my frequency fields are causing the issue but have been unable to come with a solution.
There are two different types of frequencies a user can select depending upon their "Notification Name" selection. One selection has 3 separate fields for a numerical value, time frame (week, month etc.), and a before/after selection. The other simply states instantaneous as a static text field. Regardless of which option is chosen the frequency data should be populated into one cell within the database which is then separated using piping where necessary. I'm still pretty new to C# MVC so any help is greatly appreciated.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,notificationType1,recipientTypeId,frequency")] NotificationType notificationType)
{
if (ModelState.IsValid)
{
db.NotificationType.Add(notificationType);
db.SaveChanges();
return RedirectToAction("Create");
}
ViewBag.recipientTypeId = new SelectList(db.RecipientType, "Id", "recipientRole", notificationType.recipientTypeId);
return View(notificationType);
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.notificationType1, "Notification Name", htmlAttributes: new { #class = "control-label col-md-2 helper-format" })
<div class="col-md-10" id="type_selection">
#Html.DropDownList("notificationType1", new List<SelectListItem> {
new SelectListItem { Text = "Make a Selection", Value="" },
new SelectListItem { Text = "Incomplete Documents", Value= "Incomplete Documents" },
new SelectListItem { Text = "All Documents Complete", Value = "All Documents Complete" },
new SelectListItem { Text = "Documents Requiring Action", Value = "Documents Requiring Action" }
}, new { #class = "helper-format", #id = "value_select", style = "font-family: 'Roboto', Sans Serif;" })
#Html.ValidationMessageFor(model => model.notificationType1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="frequency_group">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-3" id="frequency_group">
#Html.TextBoxFor(model => model.frequency, new { #class = "textbox-width", #placeholder = "42" })
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Day(s)", Value= "| Day"},
new SelectListItem { Text = "Week(s)", Value= "| Week"},
new SelectListItem { Text = "Month(s)", Value= "| Month"}
})
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Before", Value= "| Before"},
new SelectListItem { Text = "After", Value= "| After"}
})
</div>
<p class="col-sm-2" id="psdatetext">The Beginning</p>
</div>
<div class="form-group" id="freq_instant">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="instant_text">
<p>Instantaneous</p></div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.recipientTypeId, "Notification For", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("recipientTypeId", new List<SelectListItem>
{
new SelectListItem { Text = "Me", Value= "Me"},
new SelectListItem { Text = "Account Manager", Value="Account Manager" },
new SelectListItem { Text = "Candidate", Value= "Candidate"},
new SelectListItem { Text = "Recruiter", Value="Recruiter" },
new SelectListItem { Text = "Manager", Value= "Manager"}
})
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<div id="hovercreate">
<button type="submit" value="CREATE" class="btn btn-primary" id="createbtn">CREATE</button>
</div>
</div>
</div>
</div>
}
JS for frequency options
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
$('#frequency_group').hide()
$('#freq_instant').hide()
$('#value_select').change(function () {
var selection = $('#value_select').val();
$('#frequency_group').hide();
switch (selection) {
case 'Incomplete Documents':
$('#frequency_group').show();
break;
case 'All Documents Complete':
$('#frequency_group').show();
break;
}
});
$('#value_select').on('change', function () {
if (this.value == 'Documents Requiring Action') {
$("#freq_instant").show();
}
else {
$("#freq_instant").hide();
}
});
});
Have you placed a break-point on the method? And if so, is it triggering?
If not, try this...
From what I remember, all Controllers has a default parameter of ID which is set in the RouteConfig.cs file (App_Start/RouteConfig.cs).
There's a couple of ways to go from there.
1. Give the controller the ID parameter (e.g. (int ID))
2. Set the route value via the Route attribute
To do this you need to -
A. Add the following at the top of your RouteConfig.cs / RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//...
}
B. Add
[ValidateAntiForgeryToken]
[Route(#"Create/")]
public ActionResult Create([Bind(Include = ...
{
I would also suggest putting a break-point at the beginning of the method to see if its hitting it.
http://www.tutorialsteacher.com/mvc/routing-in-mvc
https://msdn.microsoft.com/en-us/library/system.web.mvc.routecollectionattributeroutingextensions.mapmvcattributeroutes%28v=vs.118%29.aspx
Is the Id key manually assigned? If not (for example, if it's an IDENTITY field), you shouldn't be binding it - remove Id from [Bind(Include = "...")].

How to fetch value from a list stored in a ViewBag as options(value) in a select element?

I have few items in Viewbag as a list:
var days = new List<SelectListItem>();
days.Add(new SelectListItem
{ Text = "Monday", Value = "Monday" });
days.Add(new SelectListItem
{ Text = "Tuesday", Value = "Tuesday" });
days.Add(new SelectListItem
{ Text = "Wednesday", Value = "Wednesday" });
days.Add(new SelectListItem
{ Text = "Thursday", Value = "Thursday" });
days.Add(new SelectListItem
{ Text = "Friday", Value = "Friday" });
ViewBag.DayItems = days;
I can easily pass this value to the view class using html helper generated during scaffolding in this way:
<div class="form-group">
#Html.LabelFor(model => model.Days, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Days, (List<SelectListItem>)ViewBag.DayItems, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Days, "", new { #class = "text-danger" })
</div>
</div>
Now I have a html select element:
<select>
<option value="#Value=ViewBag.DayItems"></option>
</select>
,where I want to pass the days from ViewBag as value. How should I include ViewBag.DayItems?
The below approach works for me:
#Html.DropDownList("selectedDay", ViewBag.DayItems as IEnumerable<SelectListItem>)
A rather classical approach would be:
<select>
#{
foreach (var day in ViewBag.DayItems as IEnumerable<SelectListItem>)
{
<option value="#day.Value">#day.Text</option>
}
}
</select>
Maybe it's missing optional label, try this:
#Html.DropDownListFor(model => model.Days, (List<SelectListItem>)ViewBag.DayItems, "Select one", new { #class = "form-control" })
Add an optional string 'Select one' or whatever you want from resources.

instead of id use firstname+lastname+email in select list asp.net mvc

I have feedback form with two fields : project_name and lastName of partner. The first fiels is correct(project_name) but instead lastName of second field I want there firstName+lastName+email, how to do it? At the moment there is only lastname, but I can have multiply lastnames for different partners. Below is sample of code how I create this form.
In my create method of feedbackController:
ViewBag.project_id = new SelectList(db.Projects.Where(p => p.project_id == project_id), "project_id", "name");
ViewBag.Id = new SelectList(db.Users_projects.Where(p => p.project_id == project_id && p.project_role == "partner").Select(up => new { up.AspNetUsers.FirstName,up.AspNetUsers.LastName, up.AspNetUsers.Id }), "Id", "LastName");
Here is my view how render this form:
<div class="form-horizontal">
<h4></h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.project_id, "Project: ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("project_id", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.project_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Id, " For partner : ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Id", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
ViewBag.Id =db.Users_projects
.Where(p => p.project_id == project_id &&p.project_role == "partner")
.Select(up =>
new SelectListItem {
// You may append User email also here
Text= up.AspNetUsers.FirstName +" "+up.AspNetUsers.LastName,
Value = up.AspNetUsers.Id.ToString() })
.ToList();
You can make your code more readable/maintainable by not using dynamic stuff like ViewBag and switch to a strongly typed viewmodel to pass the data between your action method and view
public class AssignProjectOwnerShipVm
{
public int SelectedPartner {set;get;}
public int SelectedProject {set;get;}
public List<SelectListItem> Projects {set;get;}
public List<SelectListItem> Partners {set;get;}
}
and in your GET action
pubilc ActionResult AssignProject()
{
var vm = new AssignProjectOwnerShipVm();
vm.Projects = db.Projects.Select(s=>new SelectListItem
{
Value = s.ProjectId.ToString(),
Text = s.ProjectName
}).ToList();
vm.Partners=db.Users_projects
.Where(p => p.project_id == project_id &&p.project_role == "partner")
.Select(up =>
new SelectListItem {
// You may append User email also here
Text= up.AspNetUsers.FirstName +" "+up.AspNetUsers.LastName,
Value = up.AspNetUsers.Id.ToString() })
.ToList();
return View(vm);
}
And your view
#model AssignProjectOwnerShipVm
#using(Html.BeginForm())
{
#Html.DrowpDownListFor(s=>s.SelectedProject,Model.Projects,"Select one")
#Html.DrowpDownListFor(s=>s.SelectedPartner,Model.Partners,"Select one")
<input type="submit" />
}
And your HttpPost
[HttpPost]
public ActionResult AssignProjecct(AssignProjectOWnerShipVm model)
{
// check for model.SelectedParter and model.SelectedProject
// to do :Save and redirect
}

Setting different default values for DropDownLists from SelectList

I have a controller which gives a SelectList to a View which then renders multiple DropDownLists for a SelectList. I now want the DropDownLists to have different Values to be selected by Default. Is there any way of doing this?
Edit: Oh and of course the values I want to be defaults are available from my Model e.g. Model.Dj1_Id etc.
Controller:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = new SelectList(db.People, "Id", "Name");
return View(prty);
}
View:
#model Musa.Models.Party
#using (Html.BeginForm("EditPartyInfo", "Events", FormMethod.Post))
{
#Html.AntiForgeryToken()
<!-- Some text input fields -->
<div class="form-group">
<label for="Dj1_Id">Dj 1</label>
<div class="form-inline">
#Html.DropDownList("Dj1_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj2_Id">Dj 2</label>
<div class="form-inline">
#Html.DropDownList("Dj2_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj3_Id">Dj 3</label>
<div class="form-inline">
#Html.DropDownList("Dj3_Id", ViewBag.People as SelectList, String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<input type="submit" class="btn btn-primary" value="Los geht's" />
}
I Actually ended up doing:
Controller:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = db.People;
return View(prty);
}
View:
/*...*/
#Html.DropDownList("Dj1_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj1_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
/*...*/
#Html.DropDownList("Dj2_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj2_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
/*...*/
#Html.DropDownList("Dj3_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj3_Id), String.Empty, new { #class = "form-control person-select", style = "width: 50%;" })
Please try;
instead of
ViewBag.People as SelectList
this;
new SelectList(ViewBag.People, "Id", "Name", "Id value to select")
as second parameter of Html.DropDownLists
SelectList has a constructor where you can pass in the selected object, so:
new SelectList(db.People, "Id", "Name", db.People.FirstOrDefault(x => x.Id == party.Dj1_Id)
I personally prefer using IEnumerable<SelectListItem> like so:
ViewBag.People = db.People.Select(x => new SelectListItem { Text = x.Name, Value = x.Id, Selected = x.Id == party.Dj1_Id);
Either way should work.

Categories