How to add new option to drop down list in MVC Razor View? - asp.net-mvc-3

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>

Related

vue.js: vue-multiselect, clearing input value after selected

I am working on my project in laravel/vue.js and I decided to use simple vue-multiselect to choose categories from my database. Thing is I want to clear the value from input field (to look for item in list).
My multiselect component:
<multiselect
v-model="value"
placeholder="Find the category"
label="category_name"
:options="categories"
#input="addReceiversFromCategory">
</multiselect>
I try to clear an v-model but it work only on first select after page load (and also it is not a smart way..).
Last thing i try was the :clear-on-select="true" but it works onlu when multiple is true (which I dont want to be true).
I think its simple to do but I didn't find any way in documentation doc
If your v-model is just modeling the value selected, then you need to use that value however you want and reset value to null. I don't really know how your component is set up but it would look something like this:
<template>
<select v-model="value" v-on:change="doSomething()">
<option :value="null">-- Select --</option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
</template>
<script>
module.exports = {
data: function(){
return {
value: null
};
},
methods: {
doSomething: function() {
if( this.value ) {
var data = this.value; // now you can work with data
this.value = null; // reset the select to null
}
}
}
}
</script>

How I can add a "quick add" button in dropdown of grocery crud?

I have two tables Categories and Products
I have made a simple relation between them so I can quickly choose from a dropdown of Categories
My question: is there a way to put an 'add new' in that dropdown?
so the user won't have to go out to the category edit section to add a category
Yes, you can use Selectize.js
Here is client side example
HTML
<select id="my-items" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS
$('#my-items').selectize({
create: function(input) {
//This function will create the category on the server side
if(create_new_category(input)){
return {
value: input,
text: input
}
}
return false;
}
});
function create_new_category(input){
alert('Category '+input+' created on server');
return true; //if created successfully otherwise return false
}
JsFiddle.
Example is with multiple select, if don`t need multiple just remove the attribute.
Also you will have to provide an ajax controller for creating new category.
If you are using Grocery Crud,
you need to overwrite the column if you want this in list view.
Example
Or to overwrite the edit field if you want it in edit view.
Example

Html.DropDownList selected value not working using ViewBag

Well, after a couple hours reading stuff over here, trying unsuccessfully all the solutions, also found this article that i thought it would save my life... nothing.
Long story short.
Here is my View (all combinations)
#Html.DropDownList("yearDropDown",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
#Html.DropDownList("yearDropDownxxx",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
#Html.DropDownList("yearDropDown",(<SelectList>)ViewBag.yearDropDown)
#Html.DropDownList("yearDropDown")
Here is my Controller
public ActionResult(int year)
{
var years = new int[] { 2007, 2008, 2009, 2010, 2011, 2012 }
.Select(x => new SelectListItem {
Text = x.ToString(),
Value = x.ToString(),
Selected=x==year }).Distinct().ToList();
years.Insert(0, new SelectListItem { Value = null, Text = "ALL YEARS" });
ViewBag.yearDropDown = new SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault());
return View();
}
Here is my rendered HTML. Selected nowhere to be found.
<select id="yearDropDown" name="yearDropDown"><option value="">ALL YEARS</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select>
Needless to mention, but i will, i checked in my Watch and SelectList actually has SelectedValue property populated with the selected year passed to the controller. But when i renders at the view, it goes to the first option.
Please, I need the solution for DropDownList, NOT for DropDownListFor. I am highlighting this because i saw other people here asking for the same help and bunch of people gave them instructions, and almost order them, to use DropDownListFor. There is a reason why i NEED to use DropDownList.
SOLUTION:
Look at my own answer.
However, here are the simple changes i made.
Controller:
ViewBag.yearDropDown = years;
View:
#Html.DropDownList("yearDropDown")
The problem may also be the name, see here.
In the Controller
ViewBag.PersonList= new SelectList(db.Person, "Id", "Name", p.PersonId);
In the View
#Html.DropDownList("PersonList",(SelectList)ViewBag.PersonList )
This will not work, you have to change the name, so it's not the same.
#Html.DropDownList("PersonList123",(SelectList)ViewBag.PersonList )
So change yearDropDown and it Will Work for you.
Best regards
Christian Lyck.
ViewBag.yearDropDown = new SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault());
Last parameter here is SelectListItem, but it must be selected value (string in your example)
SelectList Constructor (IEnumerable, String, String, Object)
I know its an old question, but I will share another solution since sometimes you have done anything correctly, but you can't see the selected value after a request and response, since your razor has bug maybe. In this condition, that I've had, you can use select-option using viewbag:
In controller I had:
ViewBag.MyData = GetAllData(strSelected);
...
and as a private function in controller I had:
private List<SelectListItem> GetAllData(List<string> selectedData)
{
return MyGetAll().Select(x =>
new SelectListItem
{
Text = x.Point,
Value = x.Amount.ToString(),
Selected = selectedPrizes.Contains(x.Amount.ToString())
})
.ToList();
}
And in .cshtml I had:
<select id="Amount" name="Amount" multiple="multiple">
#foreach (var listItem in (List<SelectListItem>)ViewBag.MyData)
{
<option value="#listItem.Value" #(listItem.Selected ? "selected" : "")>
#listItem .Text
</option>
}
</select>
I hope it will be useful for similar problems :)
Change the name of the ViewBag property to NOT match the name of the DropDownList.
Use ViewBag.yearDropDownDD instead of ViewBag.yearDropDown.
ALSO, you are creating the SelectList wrongly.
You need to pass the selected value not the array item:
ViewBag.yearDropDown = new
SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault().Value);
The first place i should've gone to learn.... and i didn't.
Here is my solution
Thank you thou for your answers. Really appreciate it. I feel like shooting my own foot now. Two hours reading blogs and it took me 2 minutes to replicate this example and worked perfectly...

asp.net helper for DropDownList won't render correctly

I'm attempting to get a dropdown list to select the correct value when the page loads.
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value"), new { #class = "selectbox", selected = Model.CounterpartyType })
However, when the page renders it always selects the first value in the dropdown list.
The html source for the page:
<select class="selectbox" id="CounterpartyTypeSelect" name="CounterpartyTypeSelect" selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">
<option value="5802239e-c601-4f1e-9067-26321213f6e6">Societa per Azioni (SpA)</option>
<option value="f8160341-4a69-436f-9882-4da31a78f1d5">Gesellschaft mit beshrankter Haftung (GmbH)</option>
<option value="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">Sociedad Anonima (SA)</option>
<option value="cdbeb1d3-301b-4884-b65a-612ddd8306f3">Private Limited Company (Ltd)</option>
<option value="1fe68d96-f31b-4859-9869-8c76a5eb1508">Corporation (Inc)</option>
<option value="9c9e5722-ab59-4d1c-a0a3-91b42a3ee721">Limitada (LTDA)</option>
<option value="0cb57339-8705-4e3a-8f6a-95e9664962b7">Public Limited Company (Plc)</option>
<option value="0924d6f1-06a9-49a3-ac05-b3e2686a0e92">Partnership</option>
<option value="c8fbe021-a8f7-4e9d-ab38-dbeb5af5a631">Limited Liability Company (LLC)</option>
<option value="30d9e22b-34f5-43c5-8471-e614dbedb6a6">Aktiengesellschaft(AG)</option>
</select>
As you can see it is putting the "selected" attribute into the outer select tag instead of on the option that matches the Id. I have another select with identical parameters (except variable names of course) and it renders correctly this way. I do not want to use DropDownListFor<T> because I have a HiddenFor field that actually submits this value in the form and javascript that sets the value to match the Select choice. I've confirmed my database is storing the values that I set correctly. What is going on?
SelectList() has an overload for you to choose the selected item. You are adding it as an HTML attribute in the helper and those get rendered to the parent select tag.
Do this:
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value", Model.CounterpartyType), new { #class = "selectbox" })
Use the overload for SelectList that takes four arguments:
new SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);
What's happening in the first line of your code new { #class = "selectbox", selected = Model.CounterpartyType } is you're providing the selected attribute as an HTML attribute of the parent select element.
So you see selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d" appearing in your first line of output, which btw doesn't do anything.
Also you're providing the value to search for in the Helper as a hardcoded string "value" instead of the actual value you need from the model. The browser will default to the first option since it can't find any value matching 'value'.
To fix this, provide Model.CounterpartyType as the third parameter to your SelectList parameter instead of 'value'.

ASP.NET MVC2 validation not working with drop down list in IE <8

I have a form with a dropdownlist rendered using Html.DropDownListFor(...). The view model field that corresponds with the dropdown list has a [Required(...)] attribute attached to it. This works fine on my local machine, but as soon as I publish to our development server, the drop down lists keep displaying the required error message, even when a value is selected in the list. This only happens in IE - Firefox submits just fine.
Any thoughts?
Relevant code
View:
<ol class="form">
<li>
<%= Html.LabelFor(x => x.ContactTitle) %>
<%= Html.DropDownListFor(x=>x.ContactTitle, Model.GetTitleOptions()) %>
<%= Html.ValidationMessageFor(x => x.ContactTitle) %>
</li>
<!-- more fields... -->
</ol>
View Model:
[Required(ErrorMessage = "Title is required")]
[DisplayName("Title")]
public string ContactTitle { get; set; }
// ...
public SelectList GetTitleOptions()
{
return new SelectList(new string[]
{
"","Dr.", "Mr.", "Ms.", "Mrs.", "Miss"
});
}
It's all pretty basic stuff... I'm at a loss.
Edit: Just discovered this bug is limited to IE 8 compatibility view (and maybe prior versions). IE 8 in standards mode works as expected...
Chalk this one up to stupidity. The code in the example produces output similar to the following:
<select>
<option></option>
<option>Dr.</option>
<option>Mr.</option>
<option>Ms.</option>
<option>Mrs.</option>
<option>Miss</option>
</select>
And the relevant MVC validation function (when a RequiredAttribute is applied to a property that corresponds to a drop down list) is:
Sys.Mvc.RequiredValidator._validateSelectInput = function Sys_Mvc_RequiredValidator$_validateSelectInput(optionElements) {
/// <param name="optionElements" type="DOMElementCollection">
/// </param>
/// <returns type="Object"></returns>
for (var i = 0; i < optionElements.length; i++) {
var element = optionElements[i];
if (element.selected) {
if (!Sys.Mvc._validationUtil.stringIsNullOrEmpty(element.value)) {
return true;
}
}
}
return false;
}
Notice the function checks element.value. In the case of the html above, the value attribute is empty because there is no value attribute on the option elements. Therefore, the validation function returns false and the error occurs. This only appears to happen in IE <8, presumably because other browsers by default assign an option element's text to the value attribute if none is specified.
The solution was to modify the way I was returning the select list items from which the drop down list was built like so:
public IEnumerable<SelectListItem> GetTitleOptions()
{
return BuildSelectListItems(new string[]
{
"","Dr.", "Mr.", "Ms.", "Mrs.", "Miss"
});
}
private List<SelectListItem> BuildSelectListItems(IEnumerable<string> values) {
return (from v in values
select new SelectListItem()
{
Text = v,
Value = v
}).ToList();
}
This results in the much more predictable HTML output:
<select>
<option value=""></option>
<option value="Dr.">Dr.</option>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select>
which of course the function validates properly.

Resources