ASP.NET MVC 4 - DropDown selected value doesn't work - c#

In my ViewModel i got two fields :
public AdTypeEnum Type { get; set; }
public IList<SelectListItem> TypeEnumList { get; set; }
That's how i fill the list :
public void SetLists()
{
TypeEnumList = new List<SelectListItem>();
TypeEnumList.Add(new SelectListItem { Value = "0", Text = "Select the type"});
foreach (var en in Enum.GetValues(typeof(AdTypeEnum)).Cast<AdTypeEnum>())
{
TypeEnumList.Add(new SelectListItem
{
Value = ((int)en).ToString(),
Text = en.ToString(),
Selected = Type == (AdTypeEnum)en ? true : false
});
}
}
And then I'm just rendering a dropdown on my View :
#Html.DropDownListFor(x => x.Type, Model.TypeEnumList, new { #class = "form-control" })
But the selected value doesn't render and the first option is always selected. When I check the select in HTML I found that no one of the options got selected attribute, but when I debug my controller method I can see that always one of the selectListItem have the propety Selected=true. Why does it suddenly disappear when my view is rendering?

Ok I already found out the result. I just had to change the Type from Enum into int and correctly populate it. Everything works! :)

Related

.NET 6 - Set SelectListItem to Selected?

I have a DropDownList which I populate like below:
Controller
IEnumerable<Category> categories = _db.Category.ToList();
var selectList = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString()
});
ViewBag.categoriesSelectList = selectList;
And use in view like so:
<select asp-for="Category" name="categoryID" asp-items="#ViewBag.categoriesSelectList" class="form-control">
<option>Vælg Kategori:</option>
</select>
However, I can't seem to figure out how I can set the already selected value, so the dropdown "starts" on that value. I tried enumerating over the selectList and changing the Selected attribute of the SelectListItem, but it doesn't work since it won't save the changes I make.
Hope my question makes sense :) thanks all.
Option 1:
Modify your code to include Selected property when creating list of SelectListItem items:
var selectList = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString(),
Selected = /* Some condition that is true when the current item should be selected */
});
Option 2:
Define a view model with structure that might be referenced in the <select> tag:
public class SelectViewModel
{
public string Category { get; set; }
public List<SelectListItem> Categories { get; set; }
}
The action method:
public IActionResult Categories()
{
var model = new SelectViewModel() ;
model.Categories = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString()
});
model.Category = ... your_code_to_set_default_selection;
return View(model);
}
The view:
#model SelectViewModel
<select asp-for="Category" asp-items="#Model.Categories"></select>
Can find some mode information in the documentation: The Select Tag Helper

DropDownListFor not selecting with decimal values

I'm working with ASP.NET MVC 5 and Entity Framework 6, and I'm having a problem with the model selected value (only for decimal values) in my views.
That only happen when i'm getting data from database, if i try to submit the form, the value get back and is correctly selected.
This is my ViewModel
public class Regulacion
{
public IEnumerable<SelectListItem> ListaPorcentajePuntos
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text="0,625%" , Value = "0,625"},
new SelectListItem { Text="1%" , Value = "1"},
new SelectListItem { Text="1,25%", Value="1,25" },
new SelectListItem { Text="2,5%" , Value = "2,5"},
new SelectListItem { Text="5%" , Value = "5"},
};
}
}
public decimal? PorcentajePunto { get; set; }
//other stuff
public Regulacion(Reg reg)
{
PorcentajePunto = reg.PorcentajePunto;
}
}
And i'm using it in the view like this
#Html.DropDownListFor(x => x.PorcentajePunto, Model.ListaPorcentajePuntos, "Please select", new { #class = "form-control"})
I'm pretty sure, the problem become when i fetch the data from EF and decimal precision, because, when I'm debugging, the PorcentajePunto property stored 5.00 instead of 5, if i manually modify the property to 5 it works perfectly.
I read this question and try to use SelectList instead of SelectListItem but wasn't the solution
How can i deal with it?
Thanks!
EDIT
I'm fetching the Regulacion data like this
using(var db = new DBTrafosContext())
{
var a = db.Reg.FirstOrDefault();
if(a != null){
Regulacion newRegulacion = new Regulacion(a);
}
}

c# - render list of checkboxes, always returned as checked

Dears,
Please could you help with below problem:
I want to render list of checkbox in my view.
#model IEnumerable<CFts.Models.CFModel>
...
#foreach (var test in ViewBag.CF_list)
{
if (test.Text != "" && test.Text != " ")
{
<div class="checkbox">
<label><input value="#test.Value" id="CF_list_" name="CF_list_" #(test.Selected == true ? "checked" : "") type="checkbox"> #test.Text</label>
</div>
}
}
OK, checkbox on the page.
CF_list generated in controller (SelectListItem)
But problem that - if send this form, at least one of checkboxes all time marked as selected. For example: 1. I selected two chekckboxed, send form - everything is OK. 2. I remove all ticks and send form - one of the checkbox (last clicked) indicated as selected.
Why?
CF_List is SelectListItem
Another question:
Please could you help me to understand very simple thing
I have model with my class:
public class VendorAssistanceViewModel
{
public string Name { get; set; }
public bool Checked { get; set; }
}
public partial class CSModel : IEntity
{
public CSModel()
{
VendorAssistances = new[]
{
new VendorAssistanceViewModel { Name = "DJ/BAND" },
new VendorAssistanceViewModel { Name = "Officiant" },
new VendorAssistanceViewModel { Name = "Florist" },
new VendorAssistanceViewModel { Name = "Photographer" },
new VendorAssistanceViewModel { Name = "Videographer" },
new VendorAssistanceViewModel { Name = "Transportation" },
}.ToList();
}
public IList VendorAssistances { get; set; }
I have view:
#model IEnumerable<CSTS.Models.CSModel>
... some html code...
and how here to show array of checkboxes from Model, using VendorAssistances ?
I know that this is very simple, I read a lot of docs, but still can not understand
Thank you!
Do not set the checked attribute, let the value attribute determine whether it is checked or not.
Change
<label><input value="#test.Value" id="CF_list_" name="CF_list_" #(test.Selected == true ? "checked" : "") type="checkbox">#test.Text</label>
To
<label><input value="#test.Value" id="c_" name="CF_list_" type="checkbox">#test.Text</label>
UPDATE: Just to make this easier to understand..
Do not use a SelectListItem for CF_List, use this instead. SelectListItem is used for drop down lists.
public class CFListCheckbox
{
public bool IsChecked { get; set; } // Add a property to know if the checkbox should be checked or not
public string Text { get; set; }
public object Value { get; set; } // Change as needed
}
In your GET action..
// Assign an ICollection<CFListCheckbox> to your ViewBag.CF_list
ICollection<CFListCheckbox> cfListCB = cfCollection.Select(r => new CFListCheckbox()
{
IsChecked = false,
Text = r.SomeProp,
Value = r.SomePropOrWhatever
}).ToList();
ViewBag.CF_list = cfListCB;
On your view, use the Html.Checkbox to create your checkboxes.
#foreach (var test in ViewBag.CF_list)
{
if (!string.IsNullOrWhiteSpace(test.Text))
{
<div class="checkbox">
<label>
#Html.Checkbox("CF_list_", test.IsChecked, new { Value = test.Value }) #test.Text
</label>
</div>
}
}
On your POST action, just set the ViewBag.ViewBag.CF_list in case your post fails and goes back to the view.
// Assign an ICollection<CFListCheckbox> to your ViewBag.CF_list
ICollection<CFListCheckbox> cfListCB = cfCollection.Select(r => new CFListCheckbox()
{
IsChecked = false,
Text = r.SomeProp,
Value = r.SomePropOrWhatever
}).ToList();
// Add logic to re-assign the IsChecked property for your ViewBag.CF_list
foreach(var entry in model.CF_list_)
{
CFListCheckbox item = cfListCB.FirstOrDefault(r => r.Text == entry.SomeProp && r.Value == entry.SomePropOrWhatever);
if(item != null)
{
item.IsChecked = true;
}
}
ViewBag.CF_list = cfListCB;
return View(model);
Please note that the sample code is just to give you an idea on what you can do. It is not absolute. Optimize it as needed.

How Do I carry dropdown value selected in Asp.net MVC

Hi I have Dropdown in Index page where user needs to select lists. Values are coming from Database. I took this dropdown value into session so I can carry this to Httppost.
Below is my code in Index page :
var activitydropdown = orderdata.uspApp_ActivityPageReportname(Convert.ToInt32(newid)).ToList();
List<SelectListItem> activitypage = new List<SelectListItem>();
if (activitydropdown != null && activitydropdown.Count > 0)
{
foreach (var activityresults in activitydropdown)
{
activitypage.Add(new SelectListItem
{
Text = activityresults.name,
Value = activityresults.id.ToString(),
});
}
}
ViewData["activitydropdown"] = activitypage;
Session["activitydropdown"] = activitypage;
And this is my code in view :
#using (Html.BeginForm("Index", "Automation", new { step = "2" }, FormMethod.Post, new { id = "frmIndex" }))
{
#Html.DropDownList("DrpaActivity", ViewData["activitydropdown"] as List<SelectListItem>, "All", new { style = "margin-left:694px;margin-bottom:20px;", onchange = "submit();" })
Now when user selects list from dropdown, i need to carry that text to my httpost index. Now in httpost index, in debug mode if i see this code :
var sessionlistautomation = Session["activitydropdown"];
I can see text and value and selected is false for every item. So how can i carry text here selected from Index to httpost, so when user selects list from dropdown, it stores that text value.
It will be available in your Request i.e.
Request["DrpaActivity"]
However I would strongly advise using ViewModels instead as they're typesafe, less room for error and easier to use.
If you create a view model, like below:
public class AViewModel
{
public string DrpaActivity { get; set; }
public List<SelectListItem> ActivitySelectList { get; set; }
}
In your Index you can return it like this:
public ActionResult Index()
{
var model = new AViewModel();
// set the select list i.e.
model.ActivitySelectList = // get from db etc
return View(model);
}
Then in your view declare the model at the top
#model AViewModel
...
Set your dropdown like this:
#Html.DropDownListFor(m => m.DrpaActivity, Model.ActivitySelectList as List<SelectListItem>, "All", new { style = "margin-left:694px;margin-bottom:20px;", onchange = "submit();" })
You can then get your selected drop-down in your post as follows:
[HttpPost]
public ActionResult Index(AViewModel model)
{
var isValid = model.DrpaActivity;
return View(model);
}

Get contents of enum to a dropdownlist

I am trying to convert my Items from Enum to a dropdownlist .Please help
public enum Colors{ red,blue,green,yellow,orange,white,black,Teal,Custom }
#Html.DropDownList("SelectedColourId", Model.ColourList, "(Select one Color)")
My ViewModel is below
myPageViewModel:BasicViewModel
{
.....
public IEnumerable<SelectListItem> ColourList{ get; set; }
.........
}
I am tried something like
myViewModel.ColourList = Enum.GetNames(typeof(Colors)).ToArray()
.Select(e => new SelectListItem() { Text = e.item, Value = e.itemindex });
But I don't know how to get itemText and its correesponding Index .Its throwing errors
In the controller, initialize the ColourList array using the Enum GetNames static method and Linq:
myPageViewModel.ColourList = Enum.GetNames(typeof(Colors))
.Select(c => new SelectListItem() { Text = c, Value = c })
.ToArray();
to add the option in dropdown from enum use the below code:
foreach (DropDownEnum enumValue in Enum.GetValues(typeof(DropDownEnum)))
{
model.SortOptions.Add(new SelectListItem()
{
Text = enumValue.ToString(),
Value = url+enumValue.ToString(),
Selected = false
});
}

Categories