How can I make my SelectListItem overload set the “Value” property to be the same as the “Text” property? - asp.net-mvc-3

I’am tryinng to do something like this in my view:
#{
string selectgedOne = ViewBag.sellectedvalue;
}
#Html.DropDownListFor(x => x.Category, Model.Categories.Select(x => new SelectListItem { Text = x.ToString(), Value = x.ToString(), Selected = x.ToString().Equals(selectgedOne.ToString()) }))
But what returns is...
System.Web.Mvc.SelectListItem
I’m sort of successful whin I use this version …
#Html.DropDownListFor(x => x.Category, Model.Categories, selectgedOne)
…here it sets the value in the list box but when I F12 the page I see that first option value is not set to the same as the text…
<select id="Category" name="Category">
<option value="">Tests</option>
<option value="In class participation">In class participation</option>
<option value="Homework">Homework</option>
<option value="Projects">Projects</option>
<option value="Tests">Tests</option>
<option value="Other">Other</option>
</select>
… so if I post this to the controller Categary will be a empty string.
How can I make my SelectListItem overload set the “Value” property to be the same as the “Text” property?
Thanks for helping.

I sent the value (assignCategory) that I want at the top of the list then...
public ActionResult Categories(int? id, int? department, String assignCategory)
{
var categories = new List<SelectListItem>();
for (int i = 0; i < rubricsList.Count(); i++)
{
categories.Add(new SelectListItem
{
Text = rubricsList[i],
Value = rubricsList[i],
Selected = true
});
}
switch (assignCategory)
{
case "A":
categories.Insert(0, new SelectListItem
{
Text = rubricsList[0],
Value = rubricsList[0],
Selected = true
});
break;
// More cases here
}
The return view is partial with a single line that looks like this:
#Html.DropDownListFor(x => x.Category, Model.Categories)
Now the first value in the dropdown list is set and can be submitted properly

Related

DropDownList Initial Value Duplicated - MVC 5

I have a #foreach in my View that makes a table. Each row has two items within it's td. When I click my Edit button, the visible item's in a row disappear (DislayFor's) and the hidden items in the row appear (DropDownList)
View Code
<td class="col-md-3">
<span class="item-display">
<span style="font-size: 17px">
#Html.DisplayFor(modelItem => item.Movie.Name)
</span>
</span>
<span class="item-field">
#Html.DropDownList("movieID", item.Movie.Name)
</span>
</td>
By doing this I can select a new value in the DropDownList and then Save that change to my Database (then hiding the DropDownList and unhiding the DisplayFor.
Everything works fine, however I have an issue with the initally selected value, it appears twice with the initial value having an actual value of 0 (which relates to nothing in the DB).
Picture Example
QUESTION:
Right now my dropdown add's a value upon clicking Edit, the item initially selected has the correct name but it is given the index of 0 (which is invalid for my database).
I want to have the initially selected item to NOT be added, but rather to set the selector of the dropdown to the CORRECT INDEX of the appropriate item. I am not sure why it duplicates my selected item twice.
Controller Code
public ActionResult Index(string Filter, string searchString)
{
if (String.IsNullOrEmpty(searchString) || String.IsNullOrEmpty(Filter) || (Int32.Parse(Filter) == 0))
{
ViewBag.employeeID = new SelectList(db.Employees, "ID", "Name", );
ViewBag.movieID = new SelectList(db.Movies, "ID", "Name", initiallySelectedValue);
ViewBag.roleID = new SelectList(db.Roles, "ID", "RoleType");
var movieemployees = db.MovieEmployees.Include(m => m.Employee).Include(m => m.Movie).Include(m => m.Role);
return View(movieemployees.ToList().OrderBy(x => x.Employee.Name));
}
else
{
ViewBag.employeeID = new SelectList(db.Employees, "ID", "Name");
ViewBag.movieID = new SelectList(db.Movies, "ID", "Name");
ViewBag.roleID = new SelectList(db.Roles, "ID", "RoleType");
var parameter = Int32.Parse(Filter);
return View(db.MovieEmployees.Include(m => m.Employee).Include(m => m.Movie).Include(m => m.Role).Where(x => (parameter == 1 && x.Movie.Name.Contains(searchString)) || (parameter == 2 && x.Employee.Name.Contains(searchString)) || (parameter == 3 && x.Role.RoleType.Contains(searchString))).Distinct().ToList().OrderBy(x => x.Employee.Name));
}
}
Your understanding of the parameters for DropDownList isn't quite correct, but you're close! The second parameter for DropDownList (in your case item.Movie.Name) is adding an option label. If you replaced that with a hard-coded string that would serve as a good example of what it's doing (you would see that string as the first option of every select input).
It sounds to me like you want to delete that last parameter since it will only end up serving as a duplicate. Your code would simply look like this:
#Html.DropDownList("movieID")
The important part of your code is where you're building the object that you're storing in ViewData with the key movieID. You didn't post your controller code, but I imagine it looks something like:
var movies = movieRepository.GetAllMovies();
ViewData["movieID"] = new SelectList(movies, "Name", "Id", initiallySelectedValue);
Where Name and Id are the names of properties on the movie object and initiallySelectedValue is rather self explanatory.
Edit
Here is an example of how I would go about solving your problem:
Controller
public ActionResult Index() {
//Get all the possible movies that can be selected
var movies = movieRepository.GetAllMovies();
//Get a list of employees with their related favorite movie record
var employeesWithFavoriteMovie = movieRepository.GetEmployeesWithMovie();
var employeeModels = new List<EmployeeModel>();
//Iterate through the list of employees and their favorite movie, and build the model
foreach (var employeeWithFavoriteMovie in employeesWithFavoriteMovie) {
employeeModels.Add(new EmployeeModel() {
FirstName = employeeWithFavoriteMovie.FirstName,
FavoriteMovieId = employeeWithFavoriteMovie.Movie.Id,
MovieSelectList = new SelectList(movies, "Name", "Id", employeeWithFavoriteMovie.Movie.Id)
});
}
return View(employeeModels);
}
View
#model IEnumerable<WebApplication1.Controllers.EmployeeModel>
#foreach (var employeeModel in Model) {
#Html.DropDownList("Test", employeeModel.MovieSelectList)
}
Notice how a SelectList was built for each employee and that each list is then populated with that employees current favorite movie id. This will now put you in a position to have a properly built SelectList for each employee.
#Html.DropDownListFor(model => model.classmasterd_HCF[i].TD_TEACHER, new SelectList(Model.Teacher, "ParamKey", "ParamValue", Model.classmasterd_HCF[i].TD_TEACHER) as SelectList, new { #class = "form-control input-sm DtlField EditableCtrl", #style = "min-width:100%;", #disabled = "disabled" })
where Teacher in Model.Teacher is a model with code in paramKey and description in paramvalue. Selected value saved in TD_TEACHER field

passing drop downlist selected value to Ajax.ActionLink

i have a dropdown list in my view which is populated through model . i want to pass the selected value to
ajax link.
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >
#item.cname</option>
}
</select>
#Ajax.ActionLink("Submit", "Someaction" , new { id = } , new AjaxOptions { UpdateTargetId = "result" })
<div id="result"></div>
how should i route selected value of dropdown ? please help
Selected change action is the client side event, so you cannot handle this event with helpers. But you can use somethink like this:
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >#item.cname</option>
}
</select>
script
$("#dd").change(function() {
var selectedVal = $(this).val();
// in here you have ddl value
// you can pass this parameter with
// ajax and update your result div
$.ajax({
url : 'Home/SomeAction',
data : { selected : selectedValue },
...
success : function(result){
$("#result").html(result);
}
});
});
controller
public ActionResult SomeAction(int selected)
{
// selected is the selected value of DDL...
//return Json/PartialView
}

how to embed telerik dropdown in telerik gridview

I am using telerik controls in my project. How to embed telerik dropdown in telerik grid view with an example project mvc3+razor(cshtml) and controller code is c#?
From Controller just using a TempData or ViewBag to pass data to the View.
List<AdjustmentReasonCodes> salesAuditReasons = new List<AdjustmentReasonCodes>();
salesAuditReasons = salesDal.SalesAuditResonCodes();
TempData["SalesAuditReason"] = salesAuditReasons;
TempData["CStatus"] = salesDal.ReadCustomerListWithRecoveryStatus(objLoginHelper.LogInForUnitCode, Convert.ToByte(ctype), Helper.DateTo(Helper.YearMonthPrevious(2)));
Now just use a list to the view page to hold the TempData
#{
List<AdjustmentReasonCodes> salesAuditReasons = new List<AdjustmentReasonCodes>();
salesAuditReasons = (List<AdjustmentReasonCodes>)TempData["SalesAuditReason"];
}
You can add Combo-box very easy using Template.
<div class="DataGridXScroll">
#{
List<GetCustomerListWithRecoveryStatus> listCustomerStatus = new List<GetCustomerListWithRecoveryStatus>();
listCustomerStatus = (List<GetCustomerListWithRecoveryStatus>)TempData["CStatus"];
if (listCustomerStatus != null)
{
#(Html.Telerik().Grid(listCustomerStatus)
.Name("grvSalesAdjustment")
.DataKeys(keys => keys.Add(k => k.CustCode))
.Columns(column =>
{
column.Bound(a => a.CustCode).Width(100).HtmlAttributes(new { #class = "GridColumnLeftAlign" }).Title("Customer ID");
column.Template(#<input type="text" class="GridTextBoxRightAlign" style="width:62px;" id="#("salesAudit" + #item.CustCode.Replace(" ", "").Replace("-", "").Trim())" value="#(#item.AuditAdjustmentWithoutDPInCurrentMonth.ToString("0"))" />).Title("Audit Adjustment").Width(80);
column.Template(#<select id="#("ddlSalesAuditReason" + #item.CustCode.Replace(" ", "").Replace("-", "").Trim())" class="DropDown">
<option value="0">--Select--</option>
#foreach (AdjustmentReasonCodes adrc in salesAuditReasons)
{
if (item.RefReasonForAuditAdjustment == adrc.ReasonCode)
{
<option value="#(adrc.ReasonCode)" selected="selected">#adrc.ReasonDescription</option>
}
else
{
<option value="#(adrc.ReasonCode)">#adrc.ReasonDescription</option>
}
}
</select>).Title("Audit Reason").Width(135);
}).Selectable()
.Pageable(page => page.PageSize(100))
.Scrollable(scroll => scroll.Height(300))
)
}
}
</div>

Html.DropDownListFor does not bind boolean SelectList

I have this code the constructs a select list as a boolean response
var responseList = new List<SelectListItem>();
responseList.Add(new SelectListItem { Text = "Going", Value = bool.TrueString});
responseList.Add(new SelectListItem { Text = "Not Going", Value = bool.FalseString });
ViewData[ViewDataKeys.ResponseTo] = vatOptionList;
In my view I use the dropdownlist helper below.
#Html.DropDownListFor(m => m.ResponseTo, (IEnumerable<SelectListItem>)ViewData[ViewDataKeys.ResponseTo], "--Select--")
this is the property on my Model class:
[Display(Name = "Response To")]
public bool ResponseTo { get; set; }
My problem is that what ever the value of my model.ResponseTo is, the dropdownlist always select the optional value.
I tried to use a checkbox helper and surprisingly it doesn't appear to be checked alse, though when I inspected the element, the checkbox value is "true"
I tried to use a textbox helper and it shows a "true" text, Which I think that my model has value and it just doesn't bind to the dropdownlist or checkbox. I need to use a dropdownlist. Anything I missed out?
Just tested this, it works:
In your action method:
var selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "Going", Value = bool.TrueString });
selectListItems.Add(new SelectListItem { Text = "Not going", Value = bool.FalseString });
ViewBag.MySelectList = new SelectList(selectListItems, "Value", "Text", viewModel.IsGoing);
In your view:
#Html.DropDownList("IsGoing", (SelectList) ViewBag.MySelectList)

How to add new option to drop down list in MVC Razor View?

I have 2 dropdown lists in MVC 3 razor view like this:
#Html.DropDownListFor(m => m.UserGroups, Model.UserGroups.Select(x => new SelectListItem() { Text = x.Name, Value = x.Id }), new { #class="pad5" })
They work fine. I have 3 changes to make -
1) First one needs a new option to be added at the top of this list.
<option value="">--pick--</option>
2) And the second one needs to select a specific option upon load.
Say I want to pre-select this option on my second list.
<option value="100">My Friends</option>
3) both dropdowns have same data source. This causing both list to have same name on the form. How do I change the name?
I am able to change the id, but the name seems not changing if I add this to the end:
new { #id="ViewGroup", #name="ViewGroup"}
If you have a viewmodel created, you can simply do for each dropdown:
#model Namespace.myViewModel
<select id="dropdownOne" name="dropdownOne">
<option value="">--pick--</option>
#foreach (var item in Model.myModel)
{
if(#item.id==100) {
<option value="#item.id" selected="selected">#item.Name</option>
}
else {
<option value="#item.id>#item.Name</option>
}
}
</select>

Resources