w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Create DropDownListFor from SelectList with default value
There exist already some discussions about that here or there. One of the problems might be using a different type than string for the key value. I had similar problems in past and I know that i solved it like this - explicitly setting the Selected property when preparing the list (in your case, AlLStatus). Would mean, for your case (in controller action): IEnumerable<SelectListItem> selectList = from s in allStatus // where ever you get this from, database etc. select new SelectListItem { Selected = (s.id == model.Item.Item.Status), Text = cs.Description, Value = s.id.ToString() }; model.AllStatus = selectList;

Categories : C#

How to get value from DropdownListFor?
The IDs (Values) are unique whereas the description is not guaranteed to be unique so therefore cannot be relied upon for accurate selection information. This is why a drop-down list will only ever return IDs (Value part of the drop-down). From there you can determine the text for each item as you populated the drop-down in the first place so must be able to tie them back up.

Categories : C#

DropDownListFor in Asp.Net MVC 4
With the help of jquery you can do it easily. First, add an id to your actionlink: @Html.ActionLink("RegisterModules", "Home", new { idempresa =5, idbanco = 10 }, new { id = "myLink" }) Now add the script to your view ( I would prefer adding it to a javascript file and bundle the file and add to this page) : <script type="text/javascript"> $(document).ready(function () { $('select[id*="Banco"]').change(function () { var lnk = $('#myLink').attr('href'); var givenval = $('select[id*="Banco"]').val(); var result = lnk.split("idbanco=") if (result.length > 1) { lnk = result[0] + "idbanco=" + givenval; } $('#myLink').attr('href', lnk); }); }); </script> And ma

Categories : Asp Net Mvc

MVC Dropdownlistfor<>
If you want to avoid the usage of model, you may simply use a ViewBag. in your action: ViewBag.DirectorId = new SelectList(ListOfItemsToAdd, "dataValueField", "dataTextField", movie.DirectorId); and in the view: <%= Html.DropDownList("VariableNameToPost", ViewBag.DirectorId) //for asp.net view engine %> @Html.DropDownList("VariableNameToPost", ViewBag.DirectorId) // for razor view engine and the action that would accept the variable would then have something like this: public ActionResult theAction(string VariableNameToPost){...} refferences: Select List Drop Down List

Categories : C#

ASP MVC check value from DropDownListFor
@Html.DropDownListFor is just a helper method, which you are using in your view to generate HTML markup. When you open the final result in the browser, it will be a <select> tag with some <option> tags inside. When the user interacts with your DropDown, one of the option tags will be marked as selected in the HTML, but there will be no request to the server and your C# code will not know about this. Depending on your requirements, you may submit the value to the server immediately after the user changes the selector, or once the whole form is submitted together with the rest of the page. You can do this using AJAX requests. You can write JavaScript, which reads the selected options from the <select> tag and passes them in the request data. You question is too specific

Categories : Asp Net Mvc

Binding each DropDownListFor within @foreach
You should use editortemplates this can be applied as the following: Move your possible answers to the SurveyQuestionClass. then you can specify an editortemplate like this: @model SurveyQuestionClass <tr> <td> @Html.DropDownListFor(m => m.Answer, Model.PossibleAnswers, new { style = "font-size: small;" }) </td> <td> @Html.Raw(Model.Question) </td> </tr> Editortemplates are partialviews which should be placed in an EditorTemplates folder in your views folder. So if this applies to your home view, the template should be located in: views > Home > EditorTemplates. Editortemplates should be named as type.cshtml. so in your case: SurveyQuestionClass.cshtml in your view, this results in simply: @Html.EditorFor(m =&g

Categories : C#

Get the text from a Html.DropDownListFor
Try attaching a click handler to the button instead: $(':submit').click(function () { var selTypeText= $("#StatusID option:selected").text(); $("#Description").val(selTypeText); }); Alternatively, you could just retrieve the description server-side using the id. Recreate the list you are storing in ViewData["statuses"] and do something like: // where list holds the same list that was set to ViewData["statuses"] list.Where(x => x.StatusID == idFromPost).First().Description

Categories : Jquery

Entity relationship in DropdownListFor
If you don't whant to modify ID by convention, than you may change a bit your code, which creates SelectList: var list = new List<SelectListItem>; var items = from n in db.Directors select new SelectListItem { Text = n.fullname, Value = n.ID }; //*Add your items to List foreach (var item in items) list.Add(item); ViewBag.Directors = list; EDITED: Don't look at my first part. Commentators were right. Your models are not connected. You need directorID property in your Movie model to make it work. Than you should change your DropDownListFor as folows: @Html.DropDownListFor(model => model.directorID, (SelectList)ViewBag.Directors, "Select")

Categories : C#

How to pass value to function using DropDownListFor
Why not just get the value in the JavaScript function you are calling using jQuery? So you could do: function VersionData() { $("DropdownListName").find(":selected").text() }

Categories : C#

DropDownListFor not behaving as expected
The problem is that all your DropDownListFor end up using the same list of options. And the list of options itself contains the selected option. So when the list is updated with the selected option for one list, all the previous ones are updated too. Use something like this instead: @Html.DropDownListFor(m => m.Phones[i].Typ, new SelectList(list1, "DataValueFieldName", "TextValueFieldName", m => m.Phones[i].Typ) This will generate a new unique list for each drop down list. Replace "DataValueFieldName" and "TextValueFieldName" with the names of the properties of the objects in list1 containing the value and text to display respectfully. If list1 is IEnumerable<SelectListItem>, then you can use "Value" and "Text".

Categories : C#

set selected value in @html.dropdownlistfor
You can pass the selected value with model object. From the action method you can return the model object as follows model obj=new model(); obj.Reason="Price"; return view(obj) In the view the item with value "Price" get selected while loading itself Or you can set the selected value using jquery $(document).ready(function(){ $("#Reason").val("Price"); });

Categories : Asp Net Mvc

DropDownListFor with an item value 0 always selected
I would look at what the type of the model.Rating property is, I am assuming it is an int. If this is an (int) type and you are not providing a value, it will be bound to a 0 when it comes across to a view. As such, when the view is processed, 0 will be marked as selected, that is what the view engine thinks the right value is and will override the selected value that you manually chose. Try making the model.Rating property a nullable int (int?) and see if you have the same issues. Secondly, you could always look into a quick jQuery function to reset the drop-down to the first provided value, but that might be a little more "hacky" than what you are looking for.

Categories : C#

Using selected value in @Html.DropDownListFor
you can't use the value coming from your Model, which is not updated on client side (and the change event happens on client) You have to do $(.select_change).change(function() { alert($(this).val());//selected value alert($(this).find('option:selected').text());//selected option text });

Categories : Asp Net Mvc

DropDownListFor MVC : How to make it work
Where is your VehicleList is being initialized? It doesn't look like DropDownListModel is being called and even if it was - what is items2 that it sets? try setting this.VehicleList in there instead.

Categories : C#

MVC 4 WebGrid DropDownLIstFor selectedValue
Your DropdownlistFor calling will the issue. Please lets check the follwing site. You should give the default value on dropdownlist level, and not on select list level. I dont remember correctly the real calling but something like this should be tryied: @Html.DropDownListFor(m => m.fk_MFID, new SelectList(Model.L_MF, "Value", "Text", item.fk_MFID), new { @class = "edit-mode" }, "Default value")

Categories : Asp Net Mvc

Generic use of DropDownListFor with reflections
I haven't had time to try this out yet, but the stumbling block may be that the code is trying to bind PropertyInfo, not the actual property on the class. I would give this a shot: foreach (var property in Model.FormModel.GetType().GetProperties()) { @Html.DropDownListFor(m => property.Name, SelectList) }

Categories : C#

Selected value for dropdownlistfor in mvc4
How will I do it using Annonymous type in ViewBag ? Overload Controller Action Method public ActionResult DropDownListFor() { ViewBag.Doors = new SelectList( new[] { new {Value = 1,Text="1-Door"}, new {Value = 2,Text="2-Door"}, new {Value = 3,Text="4-Door"}, new {Value = 4,Text="4-Door"}, new {Value = 5,Text="5-Door"}, new {Value = 6,Text="6-Door"}, new {Value = 7,Text="7-Doors"} }, "Value", "Text", 7); return View(); } View @Html.DropDownList("Doors") How will I do it using SelectListItem? Action Method

Categories : Asp Net Mvc

DropDownListFor automatic postback
I think you can simply achieve this by submitting form on change event of DropDownList Assuming myForm as you form id <script type = "text/javascript"> $(function () { $('#DropDownListForId').change(function () { $('form#myForm').submit(); }); }); </script>

Categories : Asp Net Mvc

how to use @Html.DropDownListFor with custom datatype
try this change your model to something like this public class customer { public int id { get; set; } public string SelectedName { get; set; } public IEnumerable<SelectListItem> Names { get; set; } public string address { get; set; } } In controller [HttpGet] public ActionResult Customer() { var names=//collect names from database var model = new Customer { Names = names.Select(m=> new SelectListItem { value = m.whatever value you want to get(probably Id) text = m.name you want to display }) }; return View(model); } and in view @model MvcApplication1.customer @Html.DropDownListFor(model => model.SelectedName, Model.Names)

Categories : Asp Net Mvc

Kendo-UI DropDownListFor - selected index
Have you tried setting the name of the DropDownList equal to the name of the property in your model? The Kendo Documentation suggests that "if widget's name is different than the Model's property then the ModelBinder will not be able to update the model."

Categories : Asp Net Mvc

How disable parent items on dropdownlistfor?
One approach you could take is to load up the Regions, remove the Parent items, and then assign the SelectList to the Viewbag. var regions = MyRepository.LoadRegions(); /* remove parent items from regions */ ViewBag.Regions = new SelectList(regions, "Id", "Name"); EDIT I previously misunderstood the question. You want to have headers that aren't selectable. I found this question about MVC supporting OptGroups (which I think will accomplish what you're going for). Turns out the base Html.DropDown helper doesn't support it but you can write a custom one, and in the linked question there is a sample of a custom helper for this case.

Categories : Javascript

DropDownListFor issue with selected values
A list of SelectListItems is more explicit and gives you a Selected property but it's more geared at multi-select lists and you no longer have access to the original list if your view requires it elsewhere. Take a look at SelectList. It might work better for you in some cases. You can obtain one like this: myList.ToSelectList("ID", "Description") or new SelectList(myList, "ID", "Description) Add: data-placeholder="Please Select" in the same object that contains your "style = ..." if you want a placeholder until an option is selected.

Categories : Asp Net Mvc

SelectedItem for multiple DropDownListFor not being selected
First of all, you don't have to define your own PulldownItem class. You can use SelectListItem. So, your ViewModel will be like this: public class StepFourView { #region Public Properties public IEnumerable<SelectListItem> Levels { get; set; } public IEnumerable<SelectListItem> Approaches { get; set; } public IEnumerable<SelectListItem> Types { get; set; } public StepFour StepFour{ get; set; } #endregion } Then, in your View, your drop down lists will be like this: @Html.DropDownListFor(x => x.StepFour.Assessments[i].ApproachId, new SelectList(this.Model.Approaches, "Value", "Text", Model.StepFour.Assessments[i].AppreachId)) By the way, you don't even have to loop through your Assessments. Just create a partial view for Assessment, n

Categories : C#

Adding the 'required' attribute with DropDownListFor
Use this: @Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"), new {required = "required"}) It won't achieve the shorthand <select required but it should have the same effect. Although I've found you could achieve that exact element using @Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.SomeList, "Value", "Text"), new {required = (string)null}) Which is a little ugly.

Categories : C#

My DropDownListFor does not select the SelectedValue from my SelectList
hmm, actually, on second thought, double check sublegerType_Id? I'm not sure it should be the Id. I think it needs to be the actual object. for example, this doesnt work (it defaults to the first item) List<Tuple<string, string>> NumberList = new List<Tuple<string, string>>(); for (int i = 0; i < 5; i++) { NumberList.Add(new Tuple<string, string>(i.ToString(),i.ToString())); } NumberSelectList = new SelectList(NumberList,"2"); but this works okay (it defaults to the selected item of (4,4)) List<Tuple<string, string>> NumberList = new List<Tuple<string, string>>(); Tuple<string, string> selectedObject = new Tuple<string, string>("-1","-1"); fo

Categories : Asp Net Mvc

Dependent Dropdown-Lists using DropDownListFor
DropDownListFor is evaluated on the server when the page is first rendered. You're going to have to do this at least partially client-side. You could push the calculations onto the server by doing an AJAX call when the first dropdown changes and then populate the second dropdown with the results returned by the AJAX call.

Categories : C#

How to use DropdownListFor on Multiple model view
Create a collection in the action method of controller and assign it to some Viewbag property e.g ViewBag.UserType = new SelectList(); this collection should be IEnumerable type object. Now use this ViewBag prorety from view. e.g. @Html.DropDownList ("UserType" , "Select User Type")

Categories : C#

MVC 4: How to make DropDownListFor return 0 as optionLabel value?
In the documentation for DropDownFor the optionLabel parameter (where you're passing "None") is described as: The text for a default empty item. So this is designed to always be an empty item. You will need to add an additional item into your select list in order to get a 0 value. I have used the following extension method to accomplish this (sorry untested, there may be minor errors): public IEnumerable<SelectListItem> InsertEmptyFirst(this IEnumerable<SelectListItem> list, string emptyText = "", string emptyValue = "") { return new [] { new SelectListItem { Text = emptyText, Value = emptyValue } }.Concat(list); } You would use it like this: @Html.DropDownListFor(model => model.cardReward.ID, new SelectList(ViewBag.cardReward, "Id","Name").InsertEmptyFirst("

Categories : C#

Multiple Html.dropdownlistfor with the same selectlist, set selected value
Instead of just providing Model.Difficulties to the DropDownListFor helper try passing it: new SelectList(Model.Difficulties, object selectedValue) OR another overload that lets you specify the value and text field: new SelectList(Model.Difficulties, string dataValueField, string dataTextField, object selectedValue) Use one of these as the second argument for the DropDownListFor helper. Creating a SelectList from the List<SelectListItem> allows you to set the initially selected value.

Categories : Asp Net

DropDownListFor not selecting the selected item in the SelectList
Are you sure that your ModelState for "PersonType" key before rendering the view is empty? As JimmiTh commented is going to search for the value in the ModelState first. It happened to me too, you can try @Html.DropDownList("PersonTypeFake", Function(model) model.PersonType, pTypesSelectList) and it should select the right option.

Categories : Asp Net Mvc

How to validate DropDownListFor for values bound with list
It appears you need to tag the Age property with the Required attribute and not the Ages list. Check out this answer: ASP.NET MVC 3 and validation attribute for dropdownlist with default value of 0

Categories : C#

Disable TextBoxFor after User selects a value from a DropDownListFor
You have declaration of function disableTextBox, that is fine for doing your task, but I don't see where you are calling it. If you need to call it when value of your dropDownList changing - you need to call it as handler of change event: $("#allDay").change(disableTextBox); But I think you should use jQuery and try something like this: $("#allDay").change(function(){ if($(this).val() == "true") { $("#datepicker_start").attr("disabled", "disabled"); $("#datepicker_end").attr("disabled", "disabled"); } }); For additional information about making element disabled look at this post.

Categories : Javascript

DropDownListFor not respecting Selected property of SelectList
This tends to stump people a lot - apparently the roadmap for MVC 5 includes more intuitive DropDownList helpers. When you do: @Html.DropDownListFor(x => x.TimeOption ...) ... the HTML helper will do everything in its power not to use the value you set to Selected = true in your SelectList. It will: Try to get it from ModelState - which it won't get on the GET request Try to get it from ViewData - which it will get, because you have a TimeOption property on your model. Only if both of those attempts fail, will it succumb, and use what you asked it to use. So, in your case, it will use the current value of TimeOption on your model as the selected value. Which should be fine, because that's what you asked for in your SelectList anyway ((int)Model.TimeOption), right? Wrong. Becau

Categories : C#

MVC 4 DropDownListFor Set Selected Item Based on Text
This should work. You can pass ViewBag.Titles as List<SelectListItem> from controller var jobList = new List<SelectListItem>(); foreach (var job in jobTitles) { var item = new SelectListItem(); item.Value = job.PropertyName; //the property you want to display i.e. Title item.Text = job.PropertyName; jobList.Add(item); } ViewBag.Title = jobList; and then in the view, @Html.DropDownListFor(model => model.Title, new SelectList(ViewBag.Titles,"Value","Text", Model.Title))

Categories : C#

ASP.NET mvc4 DropDownListFor pass back an object
Yes, sure, first you need to make sure SelectedProduct has Id and Name properties, and then you must make Model.Products return a list of SelectedProduct and override few methods on SelectedProduct like below: public override bool Equals(object obj) { var other = obj as ClientLookup; if (other == null) return false; return Id.Equals(other.Id); } public override int GetHashCode() { return Id.GetHashCode(); } public override string ToString() { return Id.ToString(); } By overriding these methods, and ToString especially, you are making sure that internally DropDownListFor will match the SelectedProduct in your Model.Products with the current SelectedProduct in Foo. The last piece is the ModelBinder

Categories : C#

DropDownListFor selecting wrong value when using a lambda with no argument (closure)
I would use: @Html.DropDownList("Active", new SelectList( new List<string>() { "True", "False" }, Model.Active.ToString())) I think it is shorter, clearer. When you make a SelectList you can specify the default value manually. Try the DropDownListFor too, it might work with a SelectList instead of an IEnumerable @Html.DropDownList(model => model.Active, new SelectList( new List<string>() { "True", "False" })) P.S. In the first example you have typed "modelItem => item.Active" instead of "modelItem => modelItem.Active" I guess.

Categories : Asp Net Mvc

Unable to get new selected value of @Html.DropDownListFor in case of using autobinding
You need to pass in a view model to your view with all the statuses already populated. Here is a solution to your problem. Modify it to fit in with your scenario. I hope I haven't left out anything. The code below is what I am assuming your models might look like. Your status class: public class Status { public int Id { get; set; } public string Name { get; set; } } On your view you need to pass in a view model that contains a list of all your statuses: public class YourViewModel { public int StatusId { get; set; } public IEnumerable<Status> Statuses { get; set; } } Your controller: public class YourController : Controller { private readonly IStatusRepository statusRepository; public YourController(IStatusRepository statusRepository) {

Categories : C#

call a method in some .cs file for Dropdownlistfor onchange event
You could use the window.location.href to redirect to a controller action on your application that will call this method: <script type = "text/javascript"> $(function () { $('#ddLForItems').change(function () { var item = $(this).val(); var url = '@Url.Action("SomeAction", "SomeController")?value=' + encodeURIComponent(item); window.location.href = url; }); }); </script> which will redirect to the following controller action and pass the selected value to it: public ActionResult SomeAction(string value) { ... you could call your method here } Alternatively if you don't want to be redirecting away from the current page you could use an AJAX call: <script type = "text/javascript"> $(function () {

Categories : Jquery

MVC reload issue with dropdownlistfor onchange ajax call
You can just mimic the onchange function for a jquery.ready function: $(document).ready(function() { //alert('Template knop geklikt'); var $campaignDdl = $('#campaignDdl'); var selCampID = $campaignDdl.val(); var url = $campaignDdl.data('url'); $.post(url, { selectedCampaignID: selCampID }, function (data) { $('#campaign').html(data); }) }); This should do the exact same thing as when the ddl changes, but instead take the value that is already selected and put the corresponding view in the div.

Categories : Javascript

mvc3 Html.DropDownListFor - dynamically create "value" attribute in
Each SelectList takes a dataValueField and dataTextField property in the constructor: @Html.DropDownListFor(model => model.cc_chainName, new SelectList(Model.cc_chainName, "ID", "TextualPropertyNameHere"), "Select ...") // ^^ id property and text property here You didn't supply the text property name.. so the above assumes a model similar to this: class cc_chainName { public int ID { get; set; } public string TextualPropertyNameHere { get; set; } } EDIT: In response to your comment. Consider this model: public class Product { public int Id { get; set; } public string ProductName { get; set; } } With it setup as an enumerable in a view: @model IEnumerable<YourApplica

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.