How to set a default value with Html.TextBoxFor? - c#

Simple question, if you use the Html Helper from ASP.NET MVC Framework 1 it is easy to set a default value on a textbox because there is an overload Html.TextBox(string name, object value). When I tried using the Html.TextBoxFor method, my first guess was to try the following which did not work:
<%: Html.TextBoxFor(x => x.Age, new { value = "0"}) %>
Should I just stick with Html.TextBox(string, object) for now?

Try this:
<%= Html.TextBoxFor(x => x.Age, new { #Value = "0"}) %>
note that #Value has a capital V

This should work for MVC3 & MVC4
#Html.TextBoxFor(m => m.Age, new { #Value = "12" })
If you want it to be a hidden field
#Html.TextBoxFor(m => m.Age, new { #Value = "12",#type="hidden" })

It turns out that if you don't specify the Model to the View method within your controller, it doesn't create a object for you with the default values.
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Loads default values
Instructor i = new Instructor();
return View("Create", i);
}
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Create()
{
// Does not load default values from instructor
return View("Create");
}

The default value will be the value of your Model.Age property. That's kind of the whole point.

You can simply do :
<%= Html.TextBoxFor(x => x.Age, new { #Value = "0"}) %>
or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :
#Html.TextBoxFor(x => x.Age, new { #Value = (Model==null) ? "0" : Model.Age.ToString() })

This work for me
#Html.TextBoxFor(model => model.Age, htmlAttributes: new { #Value = "" })

value="0" will set defualt value for #Html.TextBoxfor
its case sensitive
"v" should be capital
Below is working example:
#Html.TextBoxFor(m => m.Nights,
new { #min = "1", #max = "10", #type = "number", #id = "Nights", #name = "Nights", Value = "1" })

Here's how I solved it. This works if you also use this for editing.
#Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })

Using #Value is a hack, because it outputs two attributes, e.g.:
<input type="..." Value="foo" value=""/>
You should do this instead:
#Html.TextBox(Html.NameFor(p => p.FirstName).ToString(), "foo")

this worked for me , in this way we setting the default value to empty string
#Html.TextBoxFor(m => m.Id, new { #Value = "" })

If you have a partial page form for both editing and adding, then the trick I use to default value to 0 is to do the following:
#Html.TextBox("Age", Model.Age ?? 0)
That way it will be 0 if unset or the actual age if it exists.

For .net core 5 setting value in htmlAttributes seems doesnt work. But you can use workaround:
var ageTextBox = (TagBuilder) Html.TextBoxFor(x => x.Age);
ageTextBox.Attributes.Remove("value");
ageTextBox.Attributes.Add("value", "value you want to set");

Try this also, that is remove new { } and replace it with string.
<%: Html.TextBoxFor(x => x.Age,"0") %>

Related

MultiSelectList shows one value from the IEnumerable given to it with multiple values

I have a form with a MultiSelectList and I'm using .Net validation to require a selection be made amongst required other vields. When I submit, the multiple selections are sent to the controller correctly but if requirements aren't met, ModelState is invalid, I return back to the form. I'm using the below line to set the ViewBag instance of the MultiSelectList with the selections that were made. The code seems to work. However, the view only displays a single selection, the first selection, not any of the others that were sent and returned.
ViewBag.SelectedServiceLines = new MultiSelectList(db.LookUps.Where(lu => lu.RecordType == "ServLine"), "ID", "Description", funder.SelectedServiceLines.Select(i => i));
If I step through the razor code in my view I can view the ViewData and see that there is a MultiSelectList and it does have all of the selections that were sent to the controller and then returned. But only one of those selections are displayed. Below is how I'm displaying the list. I can't figure out why only one item is being displayed and not the multiple that get sent back and are in the ViewBag as "SelectedItems" for the MultiSelectList.
#Html.DropDownList("SelectedBusinessLines", null, htmlAttributes: new { #class = "form-control chosen-select", #multiple = "multiple" })
You can use either MultiSelectList or IEnumerable<SelectListItem>, depending on your choice:
// MultiSelectList approach
ViewBag.SelectedServiceLines = new MultiSelectList(db.LookUps.Where(lu => lu.RecordType == "ServLine"), "ID", "Description", funder.SelectedServiceLines.ToList());
// IEnumerable<SelectListItem> approach
ViewBag.SelectedServiceLines = db.LookUps.Where(lu => lu.RecordType == "ServLine")
.Select(i => new SelectListItem() {
Text = i.Description,
Value = i.Id,
Selected = funder.SelectedServiceLines.Contains(i.Id)
}).ToList();
Then use ListBox[For] helper instead of DropDownList[For] to create <select> element with multiple attribute:
#* MultiSelectList approach *#
#Html.ListBoxFor(model => model.SelectedBusinessLines, ViewBag.SelectedServiceLines as MultiSelectList, new { #class = "form-control chosen-select", #multiple = "multiple" })
#* IEnumerable<SelectListItem> approach *#
#Html.ListBoxFor(model => model.SelectedBusinessLines, ViewBag.SelectedServiceLines as IEnumerable<SelectListItem>, new { #class = "form-control chosen-select", #multiple = "multiple" })
Note that the ViewBag properties have dynamic type, you need to cast into respective type to avoid view rendering problem.
Side note
You may try create a MultiSelectList or IEnumerable<SelectListItem> property inside viewmodel:
public MultiSelectList SelectedServiceLines { get; set; }
And populate it with same way as ViewBag mentioned above:
var model = new ViewModel(); // use your viewmodel class name
model.SelectedServiceLines = new MultiSelectList(db.LookUps.Where(lu => lu.RecordType == "ServLine"), "ID", "Description", funder.SelectedServiceLines.ToList());
return View(model);
Then use it with ListBoxFor helper, but this time without any cast unlike ViewBag does:
#Html.ListBoxFor(model => model.SelectedBusinessLines, Model.SelectedServiceLines, new { #class = "form-control chosen-select", #multiple = "multiple" })
Can you try this instead? I've always used a List<SelectListItem> instead of a MultiSelectList:
// Use List<SelectListItem> instead
ViewBag.SelectedServiceLines =
db.LookUps
.Where(lu => lu.RecordType == "ServLine")
.Select(i => new SelectListItem() { Text = i.Description, Value = i.Id })
.ToList();
I also suggest using a ListBox instead:
#Html.ListBox("SelectedBusinessLines", ViewBag.SelectedBusinessLines, htmlAttributes: new { #class = "form-control chosen-select", #multiple = "multiple" })

DropDownListFor Not Assigning to Selected Value

I'm running into a problem where my DropDownListFor is not defaulting to the selected value that I've created in my new List. What am I doing wrong? I've looked up many of the solutions that was provide, but none seem to fit what I was doing.
Here is my Controller Code:
List<SelectListItem> queryPlanGroupList = new List<SelectListItem>();
queryPlanGroupList = (from t in db.PlanGroups
orderby t.Name ascending
select new SelectListItem()
{
Text = t.Name,
Value = t.ID.ToString(),
Selected = (t.ID == plans.PlanGroup.ID)
}).ToList();
ViewBag.PlanGroupList = queryPlanGroupList;
Here is my View Code:
<div class="form-group">
#Html.LabelFor(model => model.PlanGroup, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.PlanGroup, (List<SelectListItem>)ViewBag.PlanGroupList , "- Select one -", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PlanGroup, "", new { #class = "text-danger" })
</div>
The Html.DropDownListFor method uses the first parameter (the expression which specifies your view model proeprty) value to set the selected option. The helper method also discard any Selected attribute you set on the SelectListItems to the default value (false).
So you should set the PlanGroup property value in your GET action method to the value you want to be pre-selected when the SELECT element is rendered.
var queryPlanGroupList = (from t in db.PlanGroups
orderby t.Name ascending
select new SelectListItem()
{
Text = t.Name,
Value = t.ID.ToString()
}).ToList();
ViewBag.PlanGroupList = queryPlanGroupList;
yourViewModel.PlanGroup = plans.PlanGroup.ID;
return View(yourViewModel);
Assuming PlanGroup property of your view model is of same type as the ID property of PlanGroup class.
Another option is to use the Html.DropDownList helper, which respects the Selected attribute on the SelectListItem
The below should also work with your current action method code.
#Html.DropDownList("PlanGroupList", null, "Select one", new { #class = "form-control" })
I personally prefer to use Html.DropDownListFor over Html.DropDownList as it is more strongly typed IMHO. I also prefer view model properties instead of using ViewBag to pass the list of options :)
I believe it is because you need to set the default value using your model. In your ViewModel, set the PlanGroup to be the value you want to be selected by default.
The Selected field for a SelectList is only used for DropDownList, not DropDownListFor.
Edit: Turns out that is the case. See a similar question here.

Select value in dropdownlist based on the value returned from database ASP.NET MVC [duplicate]

As the question says:
How to set selectedValue in DropDownListFor Html helper?
Tried most of the other solutions but none worked that's why I am opening a new question.
Nothing of these helped:
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2), htmlAttributes: new { #class = "form-control" })
//Not working with or without cast
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Single(x => x.Id == 2)), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Where(x => x.Id == 2).FirstOrDefault()), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", new SelectListItem() { Value="2", Selected=true}), htmlAttributes: new { #class = "form-control" })
I would like to avoid manual creation of SelectListItems or a ViewModel just for the list if possible.
When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option.
Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using
#Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))
Note your can inspect the source code, in particular the SelectInternal() and GetSelectListWithDefaultValue() methods to see how it works in detail.
To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view
I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita and that you generate the SelectList in the controller
var model = new YourModel()
{
TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
TipPopustaId = 2 // set the selected option
}
return View(model);
so the view becomes
#Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { #class = "form-control" })
Make Sure that your return Selection Value is a String and not and int when you declare it in your model.
Example:
public class MyModel
{
public string TipPopustaId { get; set; }
}
public static class EnumHelper
{
public static SelectList EnumToSelectList<TEnum>(this Type enumType, object selectedValue)
{
return new SelectList(Enum.GetValues(enumType).Cast<TEnum>().ToList().ToDictionary(n=> n), "Key", "Value", selectedValue);
}
}
And in your View:
#Html.DropDownListFor(model => model.Role, EnumHelper.EnumToSelectList<Role>(typeof(Role), Model.Role), new { htmlAttributes = new { #class = "padding_right" } })
#Html.ValidationMessageFor(model => model.Role, "", new { #class = "text-danger" })
Instead of EnumToList use any Other List and select Key and Value of your Listtype Properties
I noticed there is no razor oriented approach, i added below
var prices = from P in Model[idx].prices.Values
where !P.Key.ToLower().Contains("san")
select new SelectListItem()
{
Text = P.Key + " Month " + (Convert.ToDecimal(P.Value) + ((Convert.ToDecimal(P.Value) / 100) * 20)).ToString("0.##") + " $",
Value = P.Key
};
prices.ToList()[0].Selected = true;
#Html.DropDownListFor(model => prices.ToList()[0], prices)
Just going to add my preferred way of doing this is to render the select statement myself as it gives greater control over the HTML, rather than using the Razor control.
<select class="form-control" id="my-id">
#foreach (var item in Model.ListOfItems) {
var selected = "";
if (item.Value == "whatever") {
selected = "selected='selected'";
}
<option #selected value="#item.Value">#item.Text</option>
}
</select>

SelectList not setting the default value in MVC [duplicate]

As the question says:
How to set selectedValue in DropDownListFor Html helper?
Tried most of the other solutions but none worked that's why I am opening a new question.
Nothing of these helped:
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2), htmlAttributes: new { #class = "form-control" })
//Not working with or without cast
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Single(x => x.Id == 2)), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", (ProjectName.Models.TipDepozita)Model.TipoviDepozita.Where(x => x.Id == 2).FirstOrDefault()), htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(m => m.TipPopustaId, new SelectList(Model.TipoviDepozita, "Id", "Naziv", new SelectListItem() { Value="2", Selected=true}), htmlAttributes: new { #class = "form-control" })
I would like to avoid manual creation of SelectListItems or a ViewModel just for the list if possible.
When you use the DropDownListFor() (or DropDownList()) method to bind to a model property, its the value of the property that sets the selected option.
Internally, the methods generate their own IEnumerable<SelectListItem> and set the Selected property based on the value of the property, and therefore setting the Selected property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using
#Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))
Note your can inspect the source code, in particular the SelectInternal() and GetSelectListWithDefaultValue() methods to see how it works in detail.
To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view
I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita and that you generate the SelectList in the controller
var model = new YourModel()
{
TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
TipPopustaId = 2 // set the selected option
}
return View(model);
so the view becomes
#Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { #class = "form-control" })
Make Sure that your return Selection Value is a String and not and int when you declare it in your model.
Example:
public class MyModel
{
public string TipPopustaId { get; set; }
}
public static class EnumHelper
{
public static SelectList EnumToSelectList<TEnum>(this Type enumType, object selectedValue)
{
return new SelectList(Enum.GetValues(enumType).Cast<TEnum>().ToList().ToDictionary(n=> n), "Key", "Value", selectedValue);
}
}
And in your View:
#Html.DropDownListFor(model => model.Role, EnumHelper.EnumToSelectList<Role>(typeof(Role), Model.Role), new { htmlAttributes = new { #class = "padding_right" } })
#Html.ValidationMessageFor(model => model.Role, "", new { #class = "text-danger" })
Instead of EnumToList use any Other List and select Key and Value of your Listtype Properties
I noticed there is no razor oriented approach, i added below
var prices = from P in Model[idx].prices.Values
where !P.Key.ToLower().Contains("san")
select new SelectListItem()
{
Text = P.Key + " Month " + (Convert.ToDecimal(P.Value) + ((Convert.ToDecimal(P.Value) / 100) * 20)).ToString("0.##") + " $",
Value = P.Key
};
prices.ToList()[0].Selected = true;
#Html.DropDownListFor(model => prices.ToList()[0], prices)
Just going to add my preferred way of doing this is to render the select statement myself as it gives greater control over the HTML, rather than using the Razor control.
<select class="form-control" id="my-id">
#foreach (var item in Model.ListOfItems) {
var selected = "";
if (item.Value == "whatever") {
selected = "selected='selected'";
}
<option #selected value="#item.Value">#item.Text</option>
}
</select>

ASP.NET MVC: DropDownListFor doesn't select any option when rendered

I have this to populate a drop down list in an ASP.NET MVC view.
C#
ViewBag.Employees = new SelectList(
_employeeRepository.GetAll(),
"ID",
"LastName",
employeeToClientContract.EmployeeID);
CSHTML
#Html.DropDownListFor(model => model.EmployeeID, ViewBag.Employees as IEnumerable<SelectListItem>, "Please select")
NOTE: For some reason this works
ViewBag.OverridePhysicians = new SelectList(
_employeeRepository.GetAll().Where(e => e.EmployeeTypes.TypeType == 1),
"ID",
"LastName",
employeeToClientContract.OverridePhysicianID);
#Html.DropDownListFor(model => model.OverridePhysicianID, ViewBag.OverridePhysicians as IEnumerable<SelectListItem>, "Please select")
Debugging this I can see that the Selected property is set to true when it should be. But when the view is rendered, none of the options in the list is selected.
Any ideas?
UPDATE: The problem wasn't with any of the control configurations. My problem was extra spaces in my URL. All I had to do was call .Trim() to fix the problem.
$('#itemsTable').bootstrapTable({
}).on('click-row.bs.table', function (e, row, $element) {
window.location.href = "/EmployeeToClientContract/Edit?employeeId=" + row[0].toString().trim() + "&clientContractId=" + row[2].toString().trim();
});
DropDownListFor Helper use model.EmployeeID value to set selected value in DropdownList. This property has value?
Also, why are facing so much difficults with SelectList? Don't you want to populate ViewBag like this:
ViewBag.Employees = _employeeRepository
.GetAll()
.Select(x => new SelectListItem
{
Text = x.LastName,
Value = x.ID.ToString(),
Selected = employeeToClientContract.EmployeeID == x.ID
});

Categories

Resources