Kendo UI Dropdown List default value from data - asp.net

I am trying to set Value or SelectedIndex based on the datasource return after Read.
This is my View
#(Html.Kendo().DropDownList.
Name("ddlUsers").
DataTextField("text").
HtmlAttributes(New With {.style = "width:500px"}).
DataValueField("id").
DataSource(Sub(s)
s.Read(Sub(r) r.Action("GetUserList", "Employees")
End Sub). ServerFiltering(True)
End Sub).Events(Sub(e) e.Change("SetHiddenUGID")) )
The method GetUserList looks like this
Shared Function GetUserList() As IList
Return db.GetDBUserList().Where(Function(w) w.value <> 0).Select(Function(s) New With {.id = s.value,.text = s.text,.isdefault = s.isdefault}).ToList()
End Function
Now GetDBUserList returns a List of Employees
Public Class Employees
Public Property value As Int64
Public Property text As String
Public Property isdefault As Int32
End Class
I want to set the default value of the dropdown based on isdefault when it's 1, any ideas?
I have tried
var dropdownlist = $("#ddlUsers").data("kendoDropDownList");
dropdownlist.select(function (dataItem) {
if (dataItem.isdefault === 1) {
$("#ddlUsers").data("kendoDropDownList").value(dataItem.id);
}
});
But it did not work.

Your DropDownList is bound to remote data, so you cannot attempt to set the value until after your read action returns with the data.
So, you have to add your code to select the default item in the dataBound event of the DropDownList, as there is not data to select until that point.
But, your function is attempting to set the value to dataItem.id...your model does not have an id field...it has value, text, and isdefault.
Also, the DropDownList select() method takes jQuery selector, an index, or a function that returns a boolean (http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#methods-select). Your function does not return anything...so it would result in nothing being selected.
Try doing this in the dataBound event of the DropDownList:
dataBound: function(e) {
var data = e.sender.dataSource.data();
e.sender.select(function (dataItem) {
return (dataItem.isdefault === 1);
});
}
Here's a working example: http://dojo.telerik.com/#Stephen/inUKI
It's using javascript initialization but you can add the dataBound event handler to your Razor initialization easily.

Related

Property to check whether a row in grid view has been modified

Is there a simple property or method to check whether a row changed or column value has been changed in my grid view. I also want to get the index of modified/changed row
You can add it to the gridview like this
<asp:GridView Name="gridview1" OnRowUpdating="GridViewUpdateEventHandler" />
If I remember correctly there is an abundance of tutorials for gridviews and how to manipulate data.
No, there is no simple property for that. But...
Here is a method for that on MSDN
You'll have to modify it for your data and your control names to verify, but it's all there, straight from the keyboard of Microsoft.
protected bool IsRowModified(GridViewRow r)
{
int currentID;
string currentLastName;
string currentFirstName;
currentID = Convert.ToInt32(GridView1.DataKeys[r.RowIndex].Value);
currentLastName = ((TextBox)r.FindControl("LastNameTextBox")).Text;
currentFirstName = ((TextBox)r.FindControl("FirstNameTextBox")).Text;
System.Data.DataRow row =
originalDataTable.Select(String.Format("EmployeeID = {0}", currentID))[0];
if (!currentLastName.Equals(row["LastName"].ToString())) { return true; }
if (!currentFirstName.Equals(row["FirstName"].ToString())) { return true; }
return false;
}

DataGrid column value not showing with labelFunction

I have a Spark DataGrid that I'm using a labelFunction with. However it's not showing any results.
var c3:GridColumn = new GridColumn("Date Added");
c3.width = 150;
//c3.dataField = "date";
c3.labelFunction = getFormattedDateNoTimeGrid;
public function getFormattedDateNoTimeGrid(item:Object, column:GridColumn):String
{
var rawDate:String = item.date;
trace("Date:" + rawDate);
return rawDate;
}
With the previous code it shows nothing but the label function is called and all the dates correctly trace out. If I remove the dateField line the column is not empty but it's not the value returned by the label function. Basically the label function is not showing the value it is supposed to.
What a pain. Flash Builder "helped" me create a item renderer for my grid column that had this function in it:
override public function prepare(hasBeenRecycled:Boolean):void {
lblData.text = data[column.dataField];
}
That function overrides the functionality of the dataField and labelFunction. I removed it and all is well. Thanks everyone for all your help.

ASP.NET - User control filed value changes at every pageload

I have a User control that contains three dropdownlists:for day,month and year. It's kind of a datepicker. It has a private field
private bool _isValidDate = false;
On dropdownlists the first items are "Day", "Month" and "Year". On SelectedIndexChanged event I check if all the selected indices are greater than 0 and if it's true I try to create a new DateTime object with values of the dropdownlists like such:
try
{
DateTime date=new DateTime(int.Parse(ddlYear.SelectedItem),
ddlMonth.SelectedIndex,
ddlDay.SelectedIndex);
_isValidDate=true;
}
catch {_isValidDate=false;}
On the form where I use this control before submitting I check for the IsValidDate property and if it's false I warn the user. The problem is the first time I set the correct date and press the button I don't get any warning as IsValidDate property is true but if I click it for the second time the IsValidDate property sets back to false and I get the warning although the date is valid. I know it's because everytime the page loads the _isValiddate filed of the control is set back to it's default value-false. How can I handle this problem?
Your property should be like this.
public Boolean IsValidDate
{
get
{
String CompleteDate = "YourYear" + "/" + "YourMonth" + "/" + "YourDay";
DateTime Dt ;
if (DateTime.TryParse(CompleteDate, out Dt))
return true;
return false;
}
}

enable html dropdown through controller in mvc

i have an scenario where i have to perform some action according to selection of the
dropdown .
for basic refrence you can use the example of country,state,city.
i am able to populate the country list at that time i have set the other two drop downs to
disable.
after the countries are populated i want to select the state.it is getting populated .
two problems
1) how to retain the state of country ddl as it is coming back to its orisnal state.
2) how to enable the drop down through my controller.
myview code
Country
<p>
<label>
State</label>
<%=Html.DropDownList("ddlState", ViewData["ddlState"] as SelectList, "--not selected--",new { onchange = "document.forms[0].submit()", disabled = "disabled" })%>
</p>
<p>
<label>
City</label>
<%=Html.DropDownList("ddlCities", ViewData["ddlCities"] as SelectList, "--not selected--", new { onchange = "document.forms[0].submit()", disabled = "disabled" })%>
</p>
my controller code
public ActionResult InsertData()
{
var customers = from c in objDetailEntity.Country
select new
{
c.Cid,
c.Cname
};
SelectList countriesList = new SelectList(customers.Take(100), "Cid", "Cname");
ViewData["ddlCountries"] = countriesList;
SelectList EmptyState = new SelectList(customers);
ViewData["ddlState"] = EmptyState;
ViewData["ddlCities"] = EmptyState;
Session["ddlSesCountry"] = countriesList;
return View();
}
//
// POST: /RegisTest/Create
[HttpPost]
public ActionResult InsertData(FormCollection collection)
{
try
{
CountryId = Convert.ToInt16(Request.Form["ddlCountries"]);
stateid = Convert.ToInt16(Request.Form["ddlState"]);
if (CountryId > 0 && stateid <= 0)
{
var stateslist = from c in objDetailEntity.State
where c.Country.Cid == CountryId
select new
{
c.Sid,
c.Sname
};
SelectList stateList = new SelectList(stateslist.Take(100), "Sid", "Sname");
ViewData["ddlState"] = stateList;
Session["StateList"] = stateList;
ViewData["ddlCities"] = stateList;
}
if (stateid > 0)
{
var citieslist = from c in objDetailEntity.City
where c.State.Sid == stateid
select new
{
c.Ctid,
c.Cityname
};
SelectList cityList = new SelectList(citieslist.Take(100), "Ctid", "Cityname");
ViewData["ddlCities"] = cityList;
ViewData["ddlState"] = Session["StateList"];
}
ViewData["ddlCountries"] = Session["ddlSesCountry"];
return View();
}
catch
{
return View();
}
}
My choice would be not to post back the form at all. I would write an action in the controller that takes a CountryID and returns a JsonResult holding a list of states. The onchange event could call a jQuery function that uses AJAX to call this action, loads the new list, and enables the second drop-down list.
However, if you stick with the postback, here's why it's not working:
The Country list isn't retaining its selected value because the view is being reloaded from scratch each time and you're setting it to "not selected." The SelectList constructor has an overload that takes a "SelectedItem" object as the fourth parameter. When you initialize your SelectList, you should pass the appropriate value to this parameter, and not force it in the View.
You need to write an "if" clause in your View to choose whether or not to enable the list based on some criteria. You could bind to a ViewModel that has a Boolean property like "EnableStates," or you could use something like the count of values in the StateList - if the count is greater than zero, enable it, for example.
A tricky thing to get used to when you move from Web Forms to MVC is that you don't have ViewState anymore - your application is stateless. There's nothing that "remembers" what value is selected in a drop-down for you, you have to set it each time you load the page.
I recommend using JSON & jQuery - like this posted answer.

ASP .NET - Retrieve value from Listview based on NewEditIndex

Using ASP.NET 3.5 ListView control.
I would like to capture the value of my table id from the currently edited row of a ListView.
A ItemEditing event has been added to the ListView.
The only value available in this event is e.NewItemIndex.
This returns 0 if the first row of the current page of the ListView is being edited.
How do I convert this 0 into the actual table id (label control value)?
I have tried:
table_id = Convert.ToString(ListView1.Items[e.NewEditIndex].FindControl("table_idLabel1"));
Can you use the DataKeyNames property instead of a label? Set the property to the name of the database field that is the key for the table, then do something like this:
table_id = ListView1.DataKeys[e.NewEditIndex].Value.ToString();
Are you sure table_idLabel1 is the correct id?
Also, you may need to look recursively as in Chris's answer. Plus, it looks like your casting the control to a string. You probably want the ID property and not the control itself.
Use FindControlRecursive (from Recursive Page.FindControl). The problem with FindControl is that it only search one layer deep.
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}

Resources