MVC3 dropdown list value no populating inside editor template - asp.net-mvc-3

I have an editor template with a dropdown:
#Html.DropDownListFor(m => m.AdmissionState, new List<SelectListItem>()
{
new SelectListItem()
{
Text = "1",
Value = "1"
},
new SelectListItem()
{
Text = "2",
Value = "2"
},
new SelectListItem()
{
Text = "3",
Value = "3"
},
}, "- Select -")
I call it from the view:
#Html.EditorFor(m => m.Licenses)
In controller I have following code:
profile.Licenses.Add(new AttorneyLicenseModel()
{
AdmissionDate = "06/14/2012",
AdmissionState = "2",
AdmissionNumber = "asd",
});
profile.Licenses.Add(new AttorneyLicenseModel()
{
AdmissionDate = "07/16/2012",
AdmissionState = "5",
AdmissionNumber = "qwe",
});
For each of the licenses I see the fields with a data populated from the model, but not for the dropdown list - there is default value is checked. What am I doing wrong? ofcourse, the code with values is extremely simlified

Try like this:
#Html.DropDownListFor(
m => m.AdmissionState,
new SelectList(
new[]
{
new { Value = "1", Text = "1" },
new { Value = "2", Text = "2" },
new { Value = "3", Text = "3" },
},
"Value",
"Text",
Model.AdmissionState
),
"- Select -"
)
And if you are interested in understanding why my code works and yours not you could read the following answer I provided yesterday to a similar question: ASP.NET MVC DropDownListFor not selecting value from model

Related

How to manually set data for kendoui treelist

I want to set the datasource for a kendoui treelist at the run time. Please check following example. If I set the datasource at the design time, I am able to see the data in the control. But if I try to set the datasource at run time, I do not see the data in the control.
<div id="treeList"></div>
<script>
var data = [ { name: "Jane Doe" }, { name: "John Doe" }];
var dataSource = new kendo.data.TreeListDataSource({
data: [ { name: "Jane Doe" }, { name: "John Doe" }]
});
$("#treeList").kendoTreeList({
columns: [
{ field: "name" },
{ command: [{ name: "edit" }] }
],
editable: true
//,dataSource: dataSource
});
var grid = $("#treelist").data("kendoTreeList");
grid.setDataSource( dataSource);
grid.dataSource = dataSource;
grid.dataSource.read();
grid.dataSource.data(data);
</script>
The problem seems to be with the selector itself. You logic was ok but for some reason, the object returned by data("kendoTreeList") was null. I updated your code to chain the data after the kendoTreeList initialization.
var dataSource = new kendo.data.TreeListDataSource({
data: [ { name: "Jane Doe" }, { name: "John Doe" }]
});
var grid = $("#treeList").kendoTreeList({
columns: [
{ field: "name" },
{ command: [{ name: "edit" }] }
],
editable: true
}).data("kendoTreeList");
grid.setDataSource(dataSource);
It's a bit odd to say but I thought your code and my code would be equivalent. Obviously, it ain't but I can't figure out why.
Your main problem is that you have the id to the DOM element set to "treeList".
var grid = $("#treelist").data("kendoTreeList");
As you can see here, you use all lowercase when setting the grid variable. That was your only problem. It should look like this:
var grid = $("#treeList").data("kendoTreeList");

#html.dropdownfor is not seleting default value

#Html.DropDownListFor(x => x.SelectedProperty, Model.Property, "Please Select")
I have the above code in asp.net mvc3 to populate a dropdown list. Data populates but the selected item is the first item of the model result. I am trying to set default selected value as "Please select". How to do that?
In your controller action you should set the value of the SelectedProperty to the value of the item you want to preselect:
model.SelectedProperty = "5";
This obviously assumes that the Porperty contains such a value:
model.Property = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
new SelectListItem { Value = "4", Text = "item 4" },
new SelectListItem { Value = "5", Text = "item 5" },
new SelectListItem { Value = "6", Text = "item 6" },
};
By setting model.SelectedProperty = "5";, the item with Value="5" will automatically be preselected by the Html.DropDownListFor helper.
If on the other hand you want to have the "Please Select" default value being shown, make sure in your controller action that the SelectedProperty is set to null and not to some value contained in the items.

Add to kendoMultiSelect

With the new kendo multiselect how would I add options to the list and make them selected?
For instance if I have a dropdown containing: 1,2,3 and I wanted to add 4 and 5 how do I do that? Do I have to destroy the multiselect, add the options and then reinit the multiselect?
Given the following multiselect definition:
var data =
[
{ text: "Africa", value: "1" },
{ text: "Europe", value: "2" },
{ text: "Asia", value: "3" },
{ text: "North America", value: "4" },
{ text: "South America", value: "5" },
{ text: "Antarctica", value: "6" },
{ text: "Australia", value: "7" }
];
var multi = $("#select").kendoMultiSelect({
dataTextField: "text",
dataValueField: "value",
dataSource: data
}).data("kendoMultiSelect");
You can use:
var values = multi.value();
For getting the list of values.
And for setting the value to South America (element with value 5) and "Asia" (element with value 3) use:
multi.value(["5", "3"])
If you want to add values to whatever it has then you need a little trick:
var multi = $("#select").kendoMultiSelect({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
value: ["1", "2", "3"]
}).data("kendoMultiSelect");
// Adding value 4 and 5 to current content
var values = multi.value().slice();
$.merge(values, ["4", "5"]);
multi.value(values);
Warning: If values 4 and 5 were already selected you will end up having them duplicated.
Just want to add some information about how to actually add new values to the multi-select.
As OnaBai points out, the code to add an item to the multi-select is
$("#SDropDown").data("kendoMultiSelect").dataSource.add({ Text: x, Value: y });
given the .cshtml
#(Html.Kendo()
.MultiSelect()
.Name("SDropDown")
.AutoBind(true)
.Placeholder("Select s...")
.DataTextField("Text")
.DataValueField("Value")
)
In order to add an item as entered in the multi-select hook the change event for the text input. Since this isn't uniquely identified, I use XPath to get the <input> element. This is hooked in document.ready (in .cshtml, so escape #):
$(document).ready(function () {
var node = document.evaluate('//select[##id="SDropDown"]/../div[contains(##class,"k-multiselect")]/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (node)
{
node.onkeypress = SChanged;
}
}
function SChanged(e)
{
// only append on enter
if (kendo.keys.ENTER == e.keyCode)
{
// updates multi-select data source
AddToOrganizations(this.value);
var multi = $("#SDropDown").data("kendoMultiSelect");
multi.dataSource.filter({}); //clear applied filter before setting value
// keep all currently selected items and append the user entered text
// (does not check for duplicates)
// Also, the new values can only be selected after the data source has
// been updated.
var values = multi.value().slice();
$.merge(values, [this.value]);
multi.value(values);
}
}

Get data from database to combobox using KendoUI for MVC3

I'm using MVC3 with KendoUI.
I can retrieve the data by passing values to combobox manually, and could see the values in the combobox when executed.
This is by passing values manually
$("#input").kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "Cotton", value: "1" },
{ text: "Polyester", value: "2" },
{ text: "Cotton/Polyester", value: "3" },
{ text: "Rib Knit", value: "4" }
],
filter: "contains",
suggest: true,
index: 3
});
Now I need to retrieve data from SQL Server 2008.
Say my Table name is Products
Product Name <-- This is my column Name followed by the values in it.
abc
def
ghi
How can I do this ?
I'm very new to this KendoUI and also to MVC.
Please Help
Thanks,
Yo mate,
The client side configuration of the combobox should be very similar to this one.
http://demos.kendoui.com/web/combobox/remotedatasource.html
e.g.
<script>
jQuery("#products").kendoComboBox({
"dataSource": {
"transport": {
"read": {
"url": "/razor/web/Home/GetProducts",
"data": function() {
return kendo.ui.ComboBox.requestData("#products");
}
}
},
"serverFiltering": true,
"filter": [],
"schema": {
"errors": "Errors"
}
},
"dataTextField": "ProductName",
"dataValueField": "ProductID",
"filter": "contains"
});​
</script>
With such configuration from the sever method you need to create an action method which returns JsonResult and the most important part is that each object in the collection should include properties with names ProductName and ProductID representing the name and id used for the Combo.
public JsonResult GetProducts(string text)
{
var northwind = new NorthwindDataContext();
var products = northwind.Products.Select(product => new ProductViewModel
{
ProductID = product.ProductID,
ProductName = product.ProductName,
UnitPrice = product.UnitPrice ?? 0,
UnitsInStock = product.UnitsInStock ?? 0,
UnitsOnOrder = product.UnitsOnOrder ?? 0,
Discontinued = product.Discontinued
});
if (!string.IsNullOrEmpty(text))
{
products = products.Where(p => p.ProductName.Contains(text));
}
return Json(products, JsonRequestBehavior.AllowGet);
}

How to select an item from DropDownListFor list? (MVC3)

I'm populating a drop down list using this code (and it works fine):
#Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text"), "Please Select a Country")
Sometimes, this view also gets data of a pre-selected country, so I want to select that country.
I tried:
#Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text", "United States"), "Please Select a Country")
But this didn't work. I also tried the value of the item, and no luck.
What am I doing wrong?
Also, is there a way to access / modify that element after creation? (using C# not javascript)
Thanks!
There are 2 properties in the Model.Countries list: the Text and the Value. So if you want to preselect a given item in the dropdown you should use the value:
#Html.DropDownListFor(
x => x.SelectedCountry,
new SelectList(Model.Countries, "Value", "Text", "us"),
"Please Select a Country"
)
which assumes that in Model.Countries you have an item with Value="us".
As an alternative you could do this inside the controller action that is returning the view:
public ActionResult Foo()
{
var model = new MyViewModel();
model.Countries = new[]
{
new SelectListItem { Value = "fr", Text = "France" },
new SelectListItem { Value = "uk", Text = "United Kingdom" },
new SelectListItem { Value = "us", Text = "United States" },
};
model.SelectedCountry = "us";
return View(model);
}
and in the view you could simply:
#Html.DropDownListFor(
x => x.SelectedCountry,
Model.Countries,
"Please Select a Country"
)
which will preselect the element with Value="us" (the third one in my example).

Resources