System.Web.MVC.SelectList how to set selected item upon creation - asp.net-mvc-3

trying to have an item in a DropDownList selected by default from within my viewmodel.
I am creating the select list in my view model using teh following overload..
public SelectList ProgramsSelectList()
{
var ddlist = new SelectList(DiversionPrograms, "DiversionProgramID", "CrimeName", new {value = "1"});
return ddlist;
}
value = 1 is just hard coded for now. I am not sure the Html.DropDownList() respects this selected item.
Razor View:
#Html.DropDownList("programSelect", Model.ProgramsSelectList(), "Choose a Program to Manage")
I must be missing something here...

Figured it out...
var ddlist = new SelectList(DiversionPrograms, "DiversionProgramID", "CrimeName", DiversionProgram.DiversionProgramID);

Related

how do I add an item to mobiscroll at runtime

I have a mobiscroll list. I added an extra button called "Add new" I want to click that button and add a new item to the mobiscroll list.
Is that possible? I've been digging through that api to no avail. I can catch the event with a custom handler and I have the mobiscroll instance available there but no way to add to it.
If so, can I add that new item as custom html? I'm thinking an input so that the user can change that newly added item.
Thanks
The "pretty" way:
/*Create the new item*/
var newOption = document.createElement("option");
newOption.value = "My Value"
newOption.innerHTML = "My Text"
/*Append the new item*/
HTMLSelectControlID.appendChild(newOption)
/*Recreate the list*/
$("#HTMLSelectControlID").scroller('destroy').scroller($.extend(scrollerConfig["select"], { }));
The "dirty" way:
/*Inject the new item*/
HTMLSelectControlID.innerHTML += "<option value='My Value'>My Text</option>"
/*Recreate the list*/
$("#HTMLSelectControlID").scroller('destroy').scroller($.extend(scrollerConfig["select"], { }));

VS2010 Coded UI Test - Test builder unable to map two checkboxes with same text

I'm trying to create a coded UI test (with VS2010 Ultimate) for a simple web form page with two checkboxes and a submit hyperlink. The checkboxes have the same text label; "I Agree".
Using the coded UI test builder to record actions, only one checkbox is captured because both checkboxes have the same text / same UIMap Name.
Using the crosshair tool to select the second checkbox, it replaces the previous checkbox instance because they have the same text / same UIMap Name.
When the test is run, the first checkbox is checked, the second is not, and the hyperlink is clicked to submitted the form (failing validation).
How can I add the second checkbox to the test map and differentiate between the two?
If there are no unique properties on the checkboxes themselves, specify the parent object of each checkbox to differentiate them.
Example:
For
<div id="box1Parent">
<input label="I Agree"/>
</div>
<div id=box2Parent">
<input label="I Agree"/>
</div>
You would define the object like this:
public HtmlCheckBox AgreementBox1()
{
HtmlDiv parent = new HtmlDiv(browser);
parent.SearchProperties["id"] = "box1Parent";
HtmlCheckBox target = new HtmlCheckBox(parent);
target.SearchProperties["label"] = "I Agree";
return target;
}
Then, do the same for the second box, but point the parent to box2Parent. This would be your code in the non-designer section of the .uitest class.
There are multiple ways to do this.
Try to find out unique property of object like id, name.
Try to find out parent control/container of checkbox, then use {TAB} or {UP}/{DOWN} keys.
Use {TAB} key of keyboard. find out previous control -> click on that control -> use {TAB} from that control to get focus on checkbox control and use {UP}/{DOWN} arrow key to navigate.
Find out text of document and click on first or second occurrence of that as per your need.
Code to find out document Text,
public string GetCurrentPageVisibleTexts()
{
var window = this.UIMap.<WindowObject>
UITestControlCollection c = window.GetChildren();
var pgContent = (string)c[0].GetProperty("OuterHtml");
var document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(pgContent);
// We don't want these in our result
var exclusionText = new string[] { "<!--", "<![CDATA", "function()", "</form>" };
var visibleTexts = new List<string>();
//var nodes = document.DocumentNode.Descendants().Where(d => !d.Name.ToLower().Equals("span"));
foreach (var elem in document.DocumentNode.Descendants())
{
// Foreach element iterate its path back till root
// and look for "display: none" attribute in each one of its parent node
// to verify whether that element or any of its parent are marked as hidden
var tempElem = elem;
while (tempElem.ParentNode != null)
{
if (tempElem.Attributes["style"] != null)
{
// if hidden attribute found then break.
if (tempElem.Attributes["style"].Value.ToLower().Contains("display: none")) break;
}
tempElem = tempElem.ParentNode;
}
// If iteration reached to head and element is found clean of hidden property then proceed with text extraction.
if (tempElem.ParentNode == null)
{
if (!exclusionText.Any(e => elem.InnerText.Contains(e))
&& (!elem.InnerText.Trim().IsNullOrEmpty())
&& (!elem.HasChildNodes))
{
visibleTexts.Add(elem.InnerText);
}
}
} // Foreach close
var completeText = string.Join(" ", visibleTexts).Replace(" ", " ");
return Regex.Replace(completeText, #"\s+", " ");
}

How can I make my dropdown list retain selected item if my list is in the ViewBag?

how can I make my dropdown list retain selected item if my list is in the ViewBag?
This first DropdownList works fine:
#Html.DropDownList("searchString", Model.Enrollments.FirstOrDefault().WeekDays.Select(s => new SelectListItem { Text = s.ToString(), Value = s.ToString(), Selected = s.ToString().Equals(selectedItemFromList) }))
And now I would like to have another DropdownList but instead of getting the list from the model I’m getting it from the view bag like this:
#Html.DropDownList("searchString", new SelectList(ViewBag.someList, "text"), "select an item").. Again this works but I want the format like the first Dropdownlist that retains te selected value…something like this…
#Html.DropDownList("searchString", ViewBag.someList.Select(t=> new SelectListItem{ Text= t.ToString(),Value =t.ToString(),Selected =t.ToString().Equals(selectedItemFromList)}))
This doesn’t work because I’m getting my list from a viewbag I suspect. Is there a way to work with ViewBag to retain my selected list item like the first example?
Better way is initializing ViewBag in controller action...
controller
ViewBag.someList = Model.Enrollments.FirstOrDefault().WeekDays
.Select(s => new SelectListItem
{
Text = s.ToString(),
Value = s.ToString(),
Selected = s.ToString().Equals(selectedItemFromList)
}
view
#Html.DropDownList("someList", ViewBag.someList as SelectList, "select one")
you can initialize selected value in controller side.
Check HERE for examples...
This solution does the same as mine except your's is implemented in the controller instead of the view. I'm able to get my list to display but what I wanted was a way to keep the selected item of the list selected upon a revisit of the view. My list is not a model property. I created it in the controller then send it to the view via the viewbag. The first example I showed was accessing the list as a model property. The new list is accessed view the viewbag. I wanted it to be configured like my first list which works ok. Since my original post I've found a solution.
Since i needed the solution in the view finally did:
#Html.DropDownList("theString", listofinstructors.Select(tch => new SelectListItem { Text = tch.ToString(), Value = tch.ToString(), Selected = tch.ToString().Equals(somethingSelected) }))

MVC 3 Bind Model property to 2 fields (e.g. Other Title)

I'm trying to achieve a very common scenario whereas given a list of options to choose from, the last one says "Other" and when selected the user is presented with the input field to specify what "other" is.
In my case, it's a list of Person's titles:
public List<string> TitleList
{
get
{
return new List<string> { "Mr", "Mrs", "Miss", "Dr", "Other" };
}
}
and what I'm trying to do is this:
#Html.DropDownListFor(m => m.Title, new SelectList(Model.TitleList), "Please select...") #Html.TextBoxFor(m => m.Title)
I want the model to bind the TextBox value when "Other" is selected in the DropDownLis, and bind to selected item in DropDownList in all other cases.
Is this achievable without adding an extra property on the Model?
a better solution is not to bind to two fields, instead, copy selected item from a drop-down into bound textbox with some clever javascript:
#Html.DropDownList("ddlTitle", new SelectList(Model.TitleList), "Please select")
#Html.TextBoxFor(m => m.Title, new { maxLength = 10 })
Javascript:
ToggleTitleFields = function () {
var title, txtTitle;
title = $('select#ddlTitle').val();
txtTitle = $('input#Title');
if (title === "Other") {
txtTitle.val("");
txtTitle.show();
return txtTitle.focus();
} else {
txtTitle.hide();
txtTitle.val(title);
return $('span[data-valmsg-for="Title"]').empty();
}
};
$(document).on("change", "select#ddlTitle", function(e) {
return ToggleTitleFields();
});
hope this helps somebody
found a client-side solution: add/remove the "name" attribute from DropDownList. Here's my coffee script:
ToggleTitleFields = () ->
if $('select#Title').val() == "Other"
$('select#Title').removeAttr('name')
else
$('select#Title').attr('name','Title')
Tsar,
Being honest, this isn't a scenario that I've had to deal with before, but is nonetheless a good one. If I were faced with this dilemma and was allowed to use a javascript solution, i'd present a previously 'hidden' textbox when other was chosen. The user would then have to enter the new value into this texbox, which on loosing focus would populate the selectlist and be selected. Then when the form was submitted, you'd have this new value still as part of the exisiting model.
Of course, you could also do a similar logic of showing the textbox when selecting other but this time, do a little logic on the httpost controller action to determine if the 'other' item was selected and then populate the model from the 'textbox' value.
Of course, both scenarios would need a heap of validation, but in principle, either approach would 'work'

LINQ Combobox Databinding behave weird

I'm having a WinForm on witch I've a DataGridView that display a list of sites. bellow that grid i've a TextBox and a Combobox, using DataBinding the textbox show the current value "Code" grid column and the combobox show the province. The combobox is filled with a list for province
The weird thing is this:
When I change the combobox selected province for another one, at the time when the focus leave the combobox, the original value of the of the combobox return. I can't find a way for the combobox to keep the changed value.
what am I doing wrong?
Here my the code of my workbench project;
private void Form1_Load(object sender, EventArgs e)
{
context = new GMR_DEVEntities();
lSite = from t in context.tblSites where t.Actif == true select t;
this.dataGridView1.DataSource = lSite;
this.dataGridView1.AutoGenerateColumns = true;
Guid ProvinceId = Guid.Parse("00000000-0001-0000-0008-000000000001");
IQueryable<tblDomVal> provinces = from prov in context.tblDomVals where prov.pTypeDomValID == ProvinceId select prov;
comboBox1.DataSource = provinces;
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "DescrFr";
textBox1.DataBindings.Add(new Binding("Text", lSite, "Code"));
comboBox1.DataBindings.Add(new Binding("SelectedValue", lSite, "pProvinceID", false, DataSourceUpdateMode.OnPropertyChanged));
}
Any help would be welcome :)
Hugo
Try creating a new binding context for you combo
BindingContext oBC = new BindingContext();
comboBox1.BindingContext = oBC;
comboBox1.DataBindings.Add(new Binding("SelectedValue", lSite, "pProvinceID", false, DataSourceUpdateMode.OnPropertyChanged));
While searching for a solution, I've discover that the problem have something to do with the Datatype (All my tables IDs are GUID), I've change the Binding to bind with a varchar field instead of the guid, and thing went good. So the problem have something to do with GUID. But I'll change my approach, and work with manual bind

Resources