Json SelectListItem add item to top of list - c#

I am returning the following Json within an ActionResult:
return Json(_lookUp.GetMgmtByIDs(_mgmtService.GetMgmt(D).ToList(), selectedIDs.ToList())
.Select(x => new SelectListItem { Text = x.SName, Value = x.SID.ToString() })
.OrderBy(y => y.Text), JsonRequestBehavior.AllowGet);
I need to add the an item to the top of the list: "Please Select" with a value of 0. I am not sure how to do this.
I know we can do the following but does not work in this case:
.Insert(0, "Please Select");

I'd say that something like this will probably work:
new[]{ new SelectListItem { Text = "Please Select", Value = "0" } }.Concat(
_lookUp.GetMgmtByIDs(_mgmtService.GetMgmt(D).ToList(), selectedIDs.ToList())
.Select(x => new SelectListItem { Text = x.SName, Value = x.SID.ToString() })
.OrderBy(y => y.Text)
)
though it might cause you some translation issue in the future
I know we can do the following but does not work in this case:
That'll work if you materialize to a List first:
var list = _lookUp.GetMgmtByIDs(_mgmtService.GetMgmt(D).ToList(), selectedIDs.ToList())
.Select(x => new SelectListItem { Text = x.SName, Value = x.SID.ToString() })
.OrderBy(y => y.Text)
.ToList();
list.Insert(0, new SelectListItem { Text = "Please Select", Value = "0" });
and then return the list

Related

ASP.NET MVC - Get Id from a dropdownlist

I'm new in ASP.NET MVC and i have a problem. I needed to get a string "Category" from a dropdownlist, that was my code:
var CList = new List<string>();
StreetFooder sf = db.StreetFooders.Single(s => s.User.UserName == this.User.Identity.Name);
var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select d.Name;
CList.AddRange(Cqry.Distinct());
ViewBag.CategoryList = new SelectList(CList);
And the view:
<div class="col-md-10">
#Html.DropDownListFor(model => model.Category, (SelectList)ViewBag.CategoryList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
And that worked for me. After that, i realized i made a mistake and changed my string Category attribute in:
public virtual Categories Type { get; set; }
Now i want to save on my db the ID instead of string, but still want to see my string when select from dropdown list...but don't know how.
Use SelectListItem to create the SelectList, there you can specify Value = your id and Text = display text
https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem(v=vs.118).aspx
var CList = new List<SelectListItem>();
StreetFooder sf = db.StreetFooders.Single(s => s.User.UserName == this.User.Identity.Name);
var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select d;
CList.AddRange(Cqry.Distinct().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = d.Name
}));
ViewBag.CategoryList = new SelectList(CList);
You can even omit using the SelectList and simply pass a List<SelectListItem> if I recall correctly.
Try this:
var cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select new { Id = d.StreetFooder.Id, Value = d.Name};
ViewBag.CategoryList = new SelectList(cqry.Distinct(), "Id", "Value");
You need to also define Id and pass it to your DropDownList. This will initialize a new instance of the SelectList class by using the specified items for the list(cquery), the data value field(Id), and the data text field(Value) and add to you ViewBag then bind it to DropDownList.
You can use it on View like this:
#Html.DropDownList("CategoryList ", null, new { #class = "form-control" })
cqry.Distinct() will work if you have duplicates on result, which means that the Id and Value in collection are same, if you need to distinct only by name, you need to use group by.
In selectList, you can pass from which property you want to bind dropdown value and text property.
var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
group d by new { names.Name } into nameGroup
select new { Name = nameGroup.Name, Id = nameGroup.FirstOrDefault().StreetFooder.Id};
ViewBag.CategoryList = new SelectList(Cqry,"Id","Name");
You were selecting Distinct name, so I have used here group by name.
As I've created anonymous object with property 'Id' and Name. Now you can bind it in SelectList.

MVC Html.DropDownListFor not binding on selecting the same value

I have a state drop down in my MVC application and calling an helper method to populate the dropdown. On selecting the same value more than one time, drop down is getting reset to the default value "Select State", instead of the correct state.
HTML View
<div>
#Html.LabelFor(m => m.Pat.StateId)
#Html.DropDownListFor(m => m.Pat.StateId, listHelper.GetState(Model.Pat.StateId))
#Html.ValidationMessageFor(m => m.Pat.StateId)
</div>
Helper code
public static IList<SelectListItem> GetStateOptions(int? selectedId = null)
{
var lookupService = DependencyResolver.Current.GetService<IConstantsHelper>();
var result = lookupService.GetAll<State>().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Text,
Selected = selectedId.HasValue && selectedId == x.Id
}).OrderBy(x => x.Text).ToList();
result.Insert(0, new SelectListItem { Value = "", Text = "Select state...", Disabled = true, Selected = result.Any(x => !x.Selected)});
return result;
}
I think the issue is in your .Any condition, because there will be non selected options in your list, so it will return true.
Try changing it to:
result.Insert(0, new SelectListItem { Value = "", Text = "Select state...", Disabled = true, Selected = !result.Any(x => x.Selected)});

Need to add another entry (--Select--) dynamically to DropDownList in my views

I'm assigning values to my dropdownlist in my views as shown below.
#Html.DropDownList("Sites", new SelectList(Model.SiteList.Select(x => new { Value = x.SiteId, Text = x.SiteName }), "Value", "Text"))
How can I add another list item called as '--Select--'
You can simply add it as the last parameter:
#Html.DropDownList("Sites",
new SelectList(Model.SiteList.Select(x =>
new { Value = x.SiteId, Text = x.SiteName }), "Value", "Text"), "--Select--");
Working Fiddle
#{
var values = Model.SiteList.Select(x => new SelectListItem() { Value = x.SiteId, Text = x.SiteName }).ToList();
values.Add(new SelectListItem() { Text = "--Select--" });
}
#Html.DropDownList("Sites", new SelectList(values, "Value", "Text"))

Dropdown not selecting correct value

what is wrong withe following code?
#Html.DropDownListFor(model => model.title, new List<SelectListItem>
{
new SelectListItem { Text = "Other" , Value = "Other"},
new SelectListItem { Text = "Mr", Value = "Mr" },
new SelectListItem { Text = "Mrs", Value = "Mrs" },
new SelectListItem { Text = "Ms", Value = "Ms" },
new SelectListItem { Text = "Miss", Value = "Miss" }
},
new { #class = "form-control" })
the above is allowing me to select and save the value to the table, but when it come to edit , the saved value is not selected
for example the existing Data was saved with "Mr" when editing it shows "Other"
why?
Try to use SelectList with this overload following way:
#Html.DropDownListFor(model => model.title, new SelectList(new List<SelectListItem>
{
new SelectListItem { Text = "Other" , Value = "Other"},
new SelectListItem { Text = "Mr", Value = "Mr" },
new SelectListItem { Text = "Mrs", Value = "Mrs" },
new SelectListItem { Text = "Ms", Value = "Ms" },
new SelectListItem { Text = "Miss", Value = "Miss" }
},
"Value",
"Text",
Model.Title),
new { #class = "form-control" })
SelectList Constructor (IEnumerable, String, String, String, Object)
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
string dataGroupField,
Object selectedValue
)
this is worst
it is working in this cause but not the one above
#Html.DropDownListFor(model => model.PreferredContact, new List<SelectListItem>
{
new SelectListItem { Text = "Other" },
new SelectListItem { Text = "Telephone", Value = "Telephone" } ,
new SelectListItem { Text = "Email", Value = "Email" },
new SelectListItem { Text = "Post", Value = "Post" }
}, new { #class = "form-control" })
okay
i found the issue
you cannot have "title" as the name. title is a property on HTML5. i renamed the field to dTitle and it works

No ViewData Item of type 'IEnumerable<SelectListItem>' that has the key xxxxxx

I have created a dropdown list in ASP.NET MVC 5 and upon submission I get the above error.
Controller code:
public ActionResult Create()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "No", Value = "0" });
items.Add(new SelectListItem { Text = "Yes", Value = "1" });
items.Add(new SelectListItem { Text = "Unconfirmed", Value = "null" });
ViewBag.DropDown = items;
return View();
}
View code:
#Html.DropDownListFor(model => model.VisitRequested, (IEnumerable<SelectListItem>)ViewBag.Dropdown, new { onClick = "showHide();" })
How would one fix this?
Replace below
#Html.DropDownListFor(model => model.VisitRequested,
(IEnumerable<SelectListItem>)ViewBag.Dropdown,
new { onClick = "showHide();" })
With
#Html.DropDownListFor(model => model.VisitRequested,
new SelectList(ViewBag.Dropdown, "Value", "Text"),
new { onClick = "showHide();" })
This will fix your issue !!
I tried this and it worked for me
public ActionResult Create()
{
var items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "No", Value = "0" });
items.Add(new SelectListItem { Text = "Yes", Value = "1" });
items.Add(new SelectListItem { Text = "Unconfirmed", Value = "null" });
ViewBag.DropDown = items;
return View();
}
with this
#Html.DropDownListFor(model => model.VisitRequested,
new SelectList(ViewBag.Dropdown, "Value", "Text"),
new { onClick = "showHide();" })

Categories

Resources