asp.net MVC set default value for dropdown list - c#

I'm displaying a dropdown list for countries, which is populated from a database call in the controller. On page load I would like the selected value to default to 'United States'. How do I do this?
Code from view:
<div class="form-group">
#Html.LabelFor(m => m.Country)
#Html.DropDownListFor(m => m.Country, new SelectList(Model.CountriesDDL, "CountryCode", "Country"), "--Select--", new { #class = "form-control" })
</div>

In your GET action, you can set the value of Country property to the CountryCode of United states (or whatever country you want to set as default) of your view model
public ActionResult Show()
{
var vm = new YourViewModel();
vm.CountriesDDL = GetCountriesFromSomeWhere();
vm.Country="United States";
return View(vm);
}
Assuming Country is of type string

Related

Razor Html.DropDownListFor automatically set the selected value

I am new to Razor, I pass dropdown list as a viewbag and another values, when drop down list show in web it has selected values but i haven't set the any selected value, I think I use same name in viewbag value and dropdownlist value,it can be happen?
This is the viewbag,here i set the values and drop downlist:
ViewBag.GlobalInstance = globalInstance;
ViewBag.LegislativeCode = legislativeCode.Trim();
ViewBag.Legislatives = new SelectList(legislativeEntities, "LegislativeCode", "LegislativeName");
This is frontend code:
#if (ViewBag.GlobalInstance == true)
{
<div class="col-xs-5 hcm-form_controller mandatory gap" >
<label for="LegislativeCode" class="w-100" mi-resourcekey="atr-LegislativeCode" >Legislative Entity</label>
#Html.DropDownListFor(m => m.LegislativeCode, ViewBag.Legislatives as SelectList, "--- Select ---", new { #class = "calc-w-100" })
</div>
}
It seems that the page model has a value for LegislativeCode,
m => m.LegislativeCode
so when there is a same LegislativeCode in the ViewBag.Legislatives, this option will be selected.

Getting the selected value from a DropDownListFor using a ViewBag list

I'm having trouble getting the data from a DropDownListFor using a ViewBag list with my model. Here is my Controller code:
[HttpGet]
public ActionResult JoinTeam()
{
var TeamList = _db.TeamModels.ToList();
SelectList list = new SelectList(TeamList, "Id", "TeamName");
ViewBag.TeamList = list;
return View();
}
And the Razor view form looks like this:
#using (Html.BeginForm("JoinTeam", "Home", FormMethod.Post))
{
#Html.TextBoxFor(m => m.DisplayName, new { #class = "form-control form-control-lg", placeholder = "Enter your Battle Net ID" })
<br/>
#Html.DropDownListFor(m => m.TeamModel, (SelectList)ViewBag.TeamList, "- Select a Team to Join -", new { #class= "form-control form-control-lg" })
<br />
<button type="submit" class="btn btn-primary" style="width:100%;text-align:center;">Submit</button>
}
The TextBoxFor helper is returning the data correctly, but whatever option I have selected in the drop down does not get passed into my post method. Does anyone have any ideas?
The post action does work as it's getting the data from the model for the TextBoxFor help, but here's what it looks like:
[HttpPost]
public async Task<ActionResult> JoinTeam(GuardianModel model)
{
try
{
string BNETId = model.DisplayName.Replace("#", "%23");
long memberId = 0;
if (ModelState.IsValid)
{
Bungie.Responses.SearchPlayersResponse member = await service.SearchPlayers(MembershipType.Blizzard, BNETId);
memberId = member[0].MembershipId;
}
using (var context = new CoCodbEntities1())
{
var g = new GuardianModel
{
MembershipId = memberId.ToString(),
DisplayName = BNETId,
MembershipType = 4,
TeamID = model.TeamModel.Id
};
TempData["UserMessage"] = ViewBag.TeamList.Id;
return RedirectToAction("Success");
}
}
catch
{
}
return View();
}
These are the values getting passed into the Post action
From the screenshot you shared, it looks like TeamModel property is the virtual navigational property of type TeamModel. You should not bother about loading that. All you need to worry about loading the forign key property value (usually a simple type like an int or so.
Your SELECT element name should be TeamID. When the form is submitted, it will map the selected option value to the TeamID property value of your model which is the foreign key property.
#Html.DropDownListFor(m => m.TeamID, (SelectList)ViewBag.TeamList,
"- Select a Team to Join -", new { #class= "form-control form-control-lg" })
While this might fix the issue, It is a good idea to use a view model instead of using your entity class.
I found the issues I was having. All I needed to get passed into the post action was the Id of the TeamModel. So I changed this line:
#Html.DropDownListFor(m => m.TeamModel.Id, (SelectList)ViewBag.TeamList, "- Select a Team to Join -", new { #class= "form-control form-control-lg" })
I just added the Id and it seemed to work.

MVC combobox and how to save it in database?

I am a beginner in MVC (but not in C#), but the project must be made in Visual Studio .NET app (MVC or WPF) using Entity Framework. I made a Database First app, but here is my problem:
In table Customers
I have Id, Title, Name, MiddleName, Surname, Address, CountryId(relationship to Table Countries[Id, Name] 1 to many), Active(bit, True/False, Checkbox)
In table Countries
Id, Name(predefined)
Another table Titles(that I made, because I couldn't hardcode dropdownlists)
Id, TitleName
My question is when I created the Controller + View, the Title is displayed as TextBox(aka #Html.Editor(...)), when I change it to #Html.DropDownList("nameHere", null, new { htmlAttributes = new { #class = "form-control" } })
Then in my GET I create a dropdown view list:
public ActionResult Create()
{
ViewBag.nameHere = new SelectList(db.Titles, "Id", "TitleName");
ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name");
return View();
}
Then in my POST I put it too:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,Name,MiddleName,Surname,Address,CountryId,Active")] Customer customer)
{
if (ModelState.IsValid)
{
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.nameHere = new SelectList(db.Titles, "Id", "TitleName", db.Title); //selects from table Titles the Id and TitleName for the field Title in Customers table? at least that's how I interpretate it
ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name", customer.CountryId); //same for Country
return View(customer);
}
But I have 3 problems:
1st one - the server returns for Title in db.Customers NULL value
2nd one - if I don't use dropdown then it will send the value from the TextBox field(but people can write whatever they want)
3rd one(when using ViewBag and ViewData) - There is no ViewData item of type 'IEnumerable' that has the key "nameHere"
I just want a simple dropdown list where I have 4 options - Ms, Mrs, Mr, Miss and when I select it and send the full form to the server(Name, MiddleName, Surname, etc), in the table Customers to save the string from the dropdown list. nothing more.
I made my db with Database First(aka creating db then Model, not around)
I managed to come up with an answer with some OOP:
Inside the controller(GET method):
List<string> ListItems = new List<string>();
ListItems.Add("Ms.");
ListItems.Add("Mrs.");
ListItems.Add("Mr.");
ListItems.Add("Miss");
SelectList Titles = new SelectList(ListItems);
ViewData["Titles"] = Titles;
Inside the View:
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Title", ViewData["Titles"] as SelectList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>

Setting the default value of an enum dropdown in Razor

I'm trying to create an Item edit screen where the user can set a property of the Item, the ItemType. Ideally, when the user returns to the screen, the dropdown would display the ItemType already associated with the Item.
As it is, regardless of what the item.ItemType is, the dropdown will not reflect that in the dropdown. Is there a way around this?
For reference, my code at the moment is:
<div class="form-group">
#Html.LabelFor(model => model.ItemType, new { #class = "control-label col-xs-4" })
<div class="col-xs-8">
#Html.DropDownListFor(model => model.ItemType, (SelectList)ViewBag.ItemType, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemType, String.Empty, new { #class = "text-danger" })
</div>
</div>
The ViewBag is set with the following:
var ItemType = Enum.GetValues(typeof(ItemType));
ViewBag.ItemType = new SelectList(ItemType);
If you're using ASP.NET MVC 5, try just using the EnumHelper.GetSelectList method. Then you don't need ViewBag.ItemType.
#Html.DropDownListFor(model => model.ItemType, EnumHelper.GetSelectList(typeof(ItemType)), new { #class = "form-control" })
If not, you might need to specify the data value and data text fields of the select list.
var itemTypes = (from ItemType i in Enum.GetValues(typeof(ItemType))
select new SelectListItem { Text = i.ToString(), Value = i.ToString() }).ToList();
ViewBag.ItemType = itemTypes;
Then since it's an IEnumerable<SelectListItem> you'll need to change your cast.
#Html.DropDownListFor(model => model.ItemType, (IEnumerable<SelectListItem>)ViewBag.ItemType, new { #class = "form-control" })
Eventually I found a fix - manual creation of the list.
<select class="form-control valid" data-val="true"
data-val-required="The Item Type field is required." id="ItemType" name="ItemType"
aria-required="true" aria-invalid="false" aria-describedby="ItemType-error">
#foreach(var item in (IEnumerable<SelectListItem>)ViewBag.ItemType)
{
<option value="#item.Value" #(item.Selected ? "selected" : "")>#item.Text</option>
}
</select>
Try to keep as much of the logic outside of the View and in the Controller.
I saw in your self answer that it looks like you have an enum selected from wihin your controller.
I have a DropDownList in one of my apps that contains a list of Enums. It also has a default value selected, but also has specific enums available to the user. The default selection can be set from within the controller.
This example is based on what my needs were, so you'll need to adapt to your case.
In the controller:
public ActionResult Index()
{
ViewBag.NominationStatuses = GetStatusSelectListForProcessView(status)
}
private SelectList GetStatusSelectListForProcessView(string status)
{
var statuses = new List<NominationStatus>(); //NominationStatus is Enum
statuses.Add(NominationStatus.NotQualified);
statuses.Add(NominationStatus.Sanitized);
statuses.Add(NominationStatus.Eligible);
statuses.Add(NominationStatus.Awarded);
var statusesSelectList = statuses
.Select(s => new SelectListItem
{
Value = s.ToString(),
Text = s.ToString()
});
return new SelectList(statusesSelectList, "Value", "Text", status);
}
In the view:
#Html.DropDownList("Status", (SelectList)ViewBag.NominationStatuses)
This approach will automatically set the default item to the enum that was selected in the controller.

Pass back multiple selected value from dropdownlist MVC 5

I have the following properties
public SelectList ListActivities { get; set; } // Will load all hobbies i,e football, golf etc and will be displayed in a dropdown
public List<string> SelectedActivities { get; set; } // Trying to set with multiple selected values.
This is my view.
<div class="col-lg-11">
#Html.DropDownListFor(m => m.UserDetails.SelectedActivities, Model.UserDetails.ListActivities, "Please Select", new { #class = "form-control", multiple = "multiple", id = "listActivities" })
</div>
The issue I have is when I selected more then one option from the ActivitiesDropdown and press submit on my page and go back to the controller the SelectedActivities is null.
Can one shed some light on this please?
For multi-select you should use Html.ListBoxFor and not a Html.DropDownListFor because Html.DropDownListFor returns a single-selection select element.
So for this to work just change your view to:
<div class="col-lg-11">
#Html.ListBoxFor(m => m.UserDetails.SelectedActivities, Model.UserDetails.ListActivities, "Please Select", new { #class = "form-control", id = "listActivities" })
</div>

Categories

Resources