Html.DropDownList selected value from a list<string> - c#

So I use a list of string to fill a DropDownList it work fine but for the edit part when the user goes to the edit view I need that Relacion have the value is have been saved on the db, selected in the DropDownList. how can dothat?
List<string> x = new List<string> { "string1", "string2", "string3", " string4" };
ViewBag.Relacion = new SelectList(x);
<div class="editor-label">
#Html.LabelFor(model => model.Relacion)
</div>
<div class="editor-field">
#Html.DropDownList("Relacion")
#Html.ValidationMessageFor(model => model.Relacion)
</div>

you need to provide values to your dropdown list not only text strings
if your model does not know about relaction selected value you may use javascrip and do something like this
<script type="text/javascript">
$(document).ready(function () {
$('select[name=Relacion]').val($('#Relaciontext').val());
}
</script>
<div class="editor-field" style="display:none" >
#Html.TextBox("Relaciontext", ViewData["statecode"])
</div>
#Html.DropDownList("Relacion")
ViewData["statecode"]="string1";
but Ideally you need to use the selected list to populate your dropdown list and then model
by creating select list
#Html.DropDownListFor(model => model.Relacion, (IEnumerable<SelectListItem>)ViewData["Relacion"])

I would suggest you to use Telerik controls. They have DropDownList, Combobox, Grid and many more. It's an open source project with many many users.
See this DEMO

Related

The data is not displayed in the select box

Description of the situation
Connecting to the database [completed]
Downloading relevant data [completed]
I try to display them in the selectbox [zero errors in the console, view as in the attached picture = empty]
I tried:
#using AppEcp.Models
<div class="dx-fieldset-header">#ViewData["2ndSubTitle"]</div>
<div class="dx-field">
<div class="dx-field-label">Members</div>
<div class="dx-field-value">
#(Html
.DevExtreme()
.SelectBox()
.DataSource(d => d
.Mvc()
.Controller("Members")
.LoadAction("Get")
.Key("Warriars")
)
.DisplayExpr("Warriars")
.ValueExpr("Warriars")
.SearchEnabled(true)
)
</div>
</div>
image description here
Your popup window is extended. It looks like you have items in SelectBox. Check out that DisplayExpr, ValueExpr has the correct values.

Persisting Collections in ViewModel

I've been struggling for quite some time now with trying to maintain a list of objects when the ViewModel is submitted back to the controller. The ViewModel receives the list of objects just fine, but when the form is submitted back to the controller the list is empty. All of the non-collection properties are available in the controller, so I'm not sure what the issue is. I have already read the guide a few people have referenced from Scott Hanselman here
From what I can see, everyone solves this by building an ActionResult and letting the model binder map the collection to a parameter:
Controller:
[HttpPost]
public ActionResult Submit(List<ConfigurationVariable> variables)
{
}
View:
#for (int i = 0; i < Model.ConfigurationVariables.Count; i++)
{
<div class="row">
<div class="col-xs-4">
<label name="#Model.ConfigurationVariables[i].Name" value="#Model.ConfigurationVariables[i].Name" />
</div>
</div>
<div class="row">
<div class="col-xs-4">
<input type="text" class="form-control" name="#Model.ConfigurationVariables[i].Value" value="#Model.ConfigurationVariables[i].Value" />
</div>
</div>
}
What I really want is to be able to pass my ViewModel back to the controller, including the ConfigurationVariables List:
Controller:
[HttpPost]
public ActionResult Submit(ReportViewModel report) //report.ConfigurationVariables is empty
{
}
View:
#for (int i = 0; i < Model.ConfigurationVariables.Count; i++)
{
<div class="row">
<div class="col-xs-4">
#Html.LabelFor(model => model.ConfigurationVariables[i].Name, new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-xs-4">
#Html.TextBoxFor(model => model.ConfigurationVariables[i].Value, new { #class = "form-control" })
</div>
</div>
}
This will be a complicated form and I can't just put every collection into the ActionResult parameters. Any help would be greatly appreciated
You need to hold the Name property in a hidden input so that it's submitted. Label values are lost.
#Html.HiddenFor(model => model.ConfigurationVariables[i].Name)
Alright, based on your comment you won't be able to utilize mvc's form binding. No worries.
Instead of this controller definition:
public ActionResult Submit(List<ConfigurationVariable> variables)
Use one of these two:
public ActionResult Submit()
public ActionResult Submit(FormCollection submittedForm)
In the first you can access the Request object, you'll need to debug and locate your variable, then you'll need some logic to parse it apart and used the values submitted.
In the second, the form collection will be made up of all the INPUT elements in your form. You will be able to parse through them directly on the object without interference from the other attributes of the Request object.
In both cases you will probably need to use #Html.TextBox, and not TextBoxFor, and you will need to dynamically populate your dropdowns in your view.
I'm not 100% sure about the Request object, but for sure on the FormCollection you will need to create an Input element for each value/collection you want submitted. Including hidden inputs for your textboxes
Your textboxes will need to be SelectListItem collections. those require a key and a value, and when they are submitted you can loop through the collection and check the .Selected attribute.
I would try with FormCollection first, and if that doesn't work fall back to the Request object.
Also note: you are not getting a viewmodel back from the form submission, you will need to rebuild it from the form elements. If you want to post prepopulated data to the view you will need to build a view model and do appropriate parsing on the view to display it.

how to make check box selection for Listbox in mvc4 Razor

i have a listbox selection in my view ,i need to hold the ctrl key for select multiple items , i am using the following code :
#Html.ListBoxFor(
m => m.SelectedSkills ,
new MultiSelectList( listItems, "Id", "Name", #Model.SelectedSkills ),
new { Multiple = "multiple" }
)
i want to put a checkbox infront of each list item,user can check/uncheck the checkbox to select/deselect an item ,and when it post the form,only the selected checkboxes values should be passed in controller action , How can i acheive this...
You can do it like this:
First method: Create html tag
<ul>
#foreach (var g in Model.AllSkills)
{
<li>
<input type="checkbox"
name="SelectedSkills"
value="#g.ID" id="#g.ID"
#{if (condition)
{><text> checked='checked' </text> } } />
<label for="#g.ID">#g.Name</label>
</li>
}
</ul>
Now you can post the form and see the selected value is stored in model.SelectedSkills field.
Second method: Using MvcCheckBoxList
<div class="editor-field">
#Html.CheckBoxListFor(model=>model.SelectedSkills,
model=>model.AllSkills,
x=>x.ID,
x=>x.Names)
</div>
For more information please see this.

How to add switch control to mvc application?

I need to add switch control to my web application.
I'm trying to use Kendo Switch control.
I want to bind my switch to a model property.
I do that with a following way:
<div class="form-group">
#Html.Label("Guest Mode:")
<label class="checkbox-inline">
#Html.CheckBoxFor(m => m.SomeProperty, new {#id = "switch"})
</label>
</div>
<script>
var switchInstance = $("#switch").kendoMobileSwitch();
</script>
I tried many ways but can not render so simply control properly (see my screenshot).
Also I tried to use only razor syntax but it rendered only a checkbox.
What is my problem and how to fix it?
Thanks for advance!
I've done it like that. The goal is to switch on/off 'disabled' attribute for some text fields. In my case this way works just fine. I hope it's useful.
In the label tag 'for' is the binding with model property method. Checkbox is bound with the model by Html helper.
<div class="custom-control custom-switch">
#Html.CheckBoxFor(m => m.Enabled, new { #class = "custom-control-input" })
<label class="custom-control-label" for="Enabled">Disable</label>
</div>
and next is jQuery script:
#section Scripts {
<script type="text/javascript">
$(document).ready(DOM_Load);
function DOM_Load(e) {
$('[data-toggle="popover"]').popover({
container: "body"
});
$("div.custom-switch").children("input").on("change", EnabledToggle_Change);
}
function EnabledToggle_Change(e) {
var inputs = $("div.container-fluid").find("input[type!='checkbox']");
var textareas = $("div.container-fluid").find("textarea");
var switchLabel = $("div.custom-switch").children(".custom-control-label");
switchLabel.text(switchLabel.text() == 'Disable' ? 'Enable' : 'Disable');
inputs.prop('disabled', (i, v) => !v);
textareas.prop('disabled', (i, v) => !v);
}
</script>
}

ListBoxFor not unselecting between posts

I have following code in View:
<div class="row form-group">
#Html.LabelFor(x => x.GroupCriteria.Name, Translation.Name, new { #class = "col-sm-4 control-label" })
<div class="col-sm-4">
#Html.ListBoxFor(m => m.GroupCriteria.Name, Model.NameList, new { #class = "multi-select-custom" })
</div>
</div>
...
<button type="submit" name="removeCriterion" value="Name">X</button>Name: #(string.Join(",", Model.GroupCriteria.Name))</button>
...
<button type="submit">#Translation.Update</button>
And in controller:
public ActionResult GetUsers(GroupCriteriaModel groupCriteria, string removeCriterion)
{
if("Name".Equals(removeCriterion)) groupCriteria.Name.Clear();
...
return View(modelWithCriterias);
}
Now what is happening:
When I select/unselect some values by clicking in select then click "Update", everything works fine: selection in returned page is same as what was posted.
Now i click "X" to clear "Name". "removeCriterion" is equal to "Name", so Name list is cleared (in debugger I see it is empty). Debugger in View: "Model.GroupCriteria.Name" is still empty, none of "Model.NameList" is "Selected" (set true). But returned HTML contains same selection as before (same items have attribute 'selected="selected"').
Is this some kind of caching done by MVC? How to avoid this?
Most likely it is being binded from ModelState, so you should clear it:
if("Name".Equals(removeCriterion))
{
groupCriteria.Name.Clear();
ModelState.Clear();
}
If you want to perform the operation in more specific way, you can use ModelState.Remove() in order to remove only the state related to your ListBox.

Categories

Resources