How to reset DropDownList Index - c#

Im using vs'12 , C# asp.net MVC-4 - Internet Template, with KendoUI EF Code First
Logic + Question: I have first and 2ndary DropDownLists (cascading ones). So many (2ndarys) will cascade off one ( main ) DropDownList. My goal is to , with script or kendo events to On main selected index change, change all other kendo DDL's back to index(0) The cascading and enabling and all of that works fine, when i switch to another control, they all empty out, but if i were to switch back they retain there values. This is not ideal for my application
need to know
Main Kendo Control
#(Html.Kendo().DropDownListFor(m => m.Tracts)
.Name("Tracts")
.HtmlAttributes(new { style = "width:300px" }) //, id = "clients"})
.OptionLabel("Select Tract...")
.DataTextField("TractName")
.DataValueField("TractID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeTracts", "ImageView");
});
})
2ndary Kendo Controls
#(Html.Kendo().DropDownListFor(m => m.LeaseholdA)
.Name("LeaseholdA")
.HtmlAttributes(new { style = "width:300px" })
.OptionLabel("Select LeaseholdA...")
.DataTextField("LeaseholdA")
.DataValueField("LeaseholdAID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetLeaseholdA", "ImageView")
.Data("filterFromTracts");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("Tracts")
)
Attempts
1 + 2 just tryed the 2 rimmed out section
function TractSelect(e) {
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
//dropdownlist.SelectedIndex(0)
dropdownlist.enable(false);
};
The selectedindex(0) attempt did what it was supposed to off the ( change event ) the select even would claim selectedIndex doesn't exist
The enable worked but when i switched back they remembered where they were. so this was ineffective

Try to use the .value property of the DropDownList(kendo)
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
dropdownlist.value(0);
These 2 lines work great
Hope this helps

the dropdownlist variable has a jquery wrapped element here
try using the below code at the same place
function TractSelect(e) {
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
dropdownlist[0].selectedIndex = 0; //Code you need to change
dropdownlist.enable(false);
};
This will make sure that you have a html element as in plain simple javascript and YES SelectedIndex is definitely not a function but property of the HTML element

I believe you should be able to set the index to 0 using the following:
$("#LeaseholdA").val(0);
This should set the dropdown to the element with a value of 0 and thus the index.
Or you can use
$("#LeaseholdA").prop('selectedIndex', 0);

Related

How to get and set multiple checkbox values based on serverside data using bootstrap multiselect plugin

Here I have dropdownlist which contains multiple values. and user can select any no of values by clicking the checkbox infront of the value as shown below.
Following is my c# code.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"), new { id = "det" , multiple= "multiple"})
$(document).ready(function() {
$('#det').multiselect();
});
When user click save button I want to get the user selected list. I am using following code to get the values.
$("#det").val()
But the above value is empty. How to get the existing selected value?
And also I want to show the values as selected based on server side values.
I am creating model and set model property with hardcoded values as below.
model.Detail = "Cheese, Tomatoes";
But these values are not getting selected in dropdownlist as well.
Used plugin here - link
Any help?
Thanks.
You need to add multiple= "multiple" in the attributes for multiselect to work.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"),
new { id = "det", multiple= "multiple" });
to set the values:
<script>
var selectedValues = #model.Detail;
var dataarray = selectedValues.split(",");
// Set the value
$("#det").val(dataarray);
$("#det").multiselect("refresh");
</script>
First of all, use #Html.ListBoxFor that works best with Multiselect js.
In order to get the values for selected options, I have created the following client side code which returns list of value in form of String arrays
function GetDropDownVal() {
var selectidList = [];
var selectedItem = $("#ListQueCatId").val();
// .multiselect("getChecked") can also be used.
if (selectedItem != null) {
for (var i = 0; i < selectedItem.length; i++) {
selectidList.push(selectedItem[i]);
}
}
return selectidList;
}
This is how I have implemented the code
View Side Code
#Html.ListBoxFor(m => m.ListQueCatId, (SelectList)ViewBag.AllQueCat as MultiSelectList, new { #class = "form-control listQueCatIdDdl" })
Javascript Code
$(".listQueCatIdDdl").multiselect({ noneSelectedText: "--Select Category(s)--" });
Also, make sure to bind a model property of Type List in my case, ListQueCatId is List< Guid>, hence while you post the form, you will get the selected values in your model.
Also, I don't think there is need to add multiple attribute as the plugin is meant for selecting multiple values.

How can I conditionally change the values of a dropdown in a Kendo Grid?

I'm developing a project with ASP MVC 5, Kendo UI, and some layers. The main idea is that after I chose a value from a dropdown column in a Kendo Grid for example:
columns.Bound(b => b.Country).ClientTemplate("#=Country.Name#");
It should update a second and third column based on the previous selection:
columns.Bound(b => b.Category).ClientTemplate("#=Category.Name#");
columns.Bound(b => b.Client).ClientTemplate("#=Client.Name#");
I haven't been able to find any example or idea in the Telerik documentation or forums:
Grid/Events
Grid / Editing custom editor
Refresh/Replace DataSource of Foreignkey DropDown List
I read this example too with a normal dropdown:
Kendo UI DropDownList on a change to trigger event
Has anyone experienced something like this? My current idea is to create N number of Editor Templates:
#model Kendo.Mvc.Examples.Models.CategoryViewModel
#(Html.Kendo().DropDownListFor(m => m)
.DataValueField("CategoryID")
.DataTextField("CategoryName")
.BindTo((System.Collections.IEnumerable)ViewData["categories"])
)
With each of the possible Countries, however, it could be really inefficient and I still don't know how to trigger the on Change event.
After a long research, I was able to find a solution in this example:
Grid InLine and PopUp Editing using Cascading DropDownLists
However, it wasn't just copy and paste, I still don't know why this example is not available in the official FAQ Telerik page, but I'd like to provide the key point in order to do it:
1) You must select the InLine or PopUp edit mode:
.Editable(editable => editable.Mode(GridEditMode.InLine))
Why? Because when you are going to edit or add the line:
The cascade Drop downs are fully linked to the ID, for example:
2) Next, your new column in the grid is going to look this one:
columns.Bound(b => b.CategoryID).ClientTemplate("#=Category.Name#");
Be careful, before I we used the class as Category instead of the CategoryID, the ID is the crucial point.
3) You need to change the previous approach from adding the hint to the class to the ID of the it, for example:
Non-cascade approach:
[UIHint("ClientStatus")]
public Statuses Status { get; set; }
public int StatusID { get; set; }
Cascade approach:
public Statuses Status { get; set; }
[UIHint("ClientStatus")]
public int StatusID { get; set; }
3) The editor template from the cascade approaches should look like this:
Basic one:
#model int
#(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.DataValueField("CategoriesID")
.DataTextField("Name")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("PopulateCategories", "FullView"))
.ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
Cascade ones:
#model int
#(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.DataValueField("ID")
.DataTextField("Name")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("PopulateStatuses", "FullView").Data("filterCategories"))
.ServerFiltering(true);
})
.CascadeFrom("CategoriesID")
)
#Html.ValidationMessageFor(m => m)
4) The cascade is calling a JavaScript function that looks like this:
function filterCategories() {
return {
categoriesID: $("#CategoriesID").data("kendoDropDownList").value()
};
}
Where CategoriesID is the ID of the first drop down, which is generated when we edit or add a new line.
4) Finally, we need to share a JSON as a result:
First drop down:
public JsonResult PopulateCategories()
{
return Json(CategoriesData.GetCategories(), JsonRequestBehavior.AllowGet);
}
Second and further drop downs:
public JsonResult PopulateStatuses(int categoryID)
{
return Json(StatusesData.GetStatuses(categoryID), JsonRequestBehavior.AllowGet);
}
I used the following approach for styling individual cells of grid with a template. I think you can apply this logic in order to change the values in DropDownList.
UI for Javascript:
{
field: "EmployeeName", type: "string", width: "55px", title: "Employee Name",
template: "#= GetEditTemplate(data) #"
}
UI for MVC:
...
columns.Bound(t => t.EmployeeName).Title("Status Name").Template(#<text></text>)
.ClientTemplate("#= GetEditTemplate(data)#").Width("55px");
...
Example: Here data parameter is passed to the Javascript method and used in condition:
<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
var html;
if (data.StatusID == 1) {
html = kendo.format(
"<span class='text-success'>" +
data.EmployeeName
+ "</span>"
);
}
else {
html = kendo.format(
"<span class='text-danger'>Cancel</span>"
);
}
return html;
}
</script>
For more information you might have a look at How Do I Have Conditional Logic in a Column Client Template?. Hope this helps...

Add prefix to control id and still have it bind MVC Razor

I have a case where I have a page displaying an order and tabs that display the order details. The order details are quite complex and since they are the same layout, I want to use a partial view or editor template that will generate the form.
The problem is the result is multiple duplicate form input id's are generated (one for each order detail. For example, I have:
foreach (var orderDetail in Model.OrderDetils)
{
#Html.EditorFor(model => orderDetail, "WorkOrder", orderDetail)
}
I've read much about this and see solutions where it is recommended to use an editortemplate, but that solution only works when you have the same form to render, but passing it different model properties so the control id's prefixes will differ...ie. like this solution.
In my case, this won't work as the model property I am passing is always the same.
So how else can I create unique Id's in the partial or editor template that will also bind.
I know instead of:
#Html.EditorFor(model => model.WOHdr.Attribute1)
I could do:
#Html.TextBoxFor(model => model.WOHdr.Attribute1, new { id = Model.Id + "_Attribute1" })
But then it won't bind when it passes to the controller.
Thoughts?
Try this
#Html.TextBoxFor(model => model.WOHdr.Attribute1, new { #id = #Model.Id + "_Attribute1" })
Use "#"+dynamic value. Now You will get unique Id's
In EditorFor you can use like this
#Html.EditorFor(model => model.WOHdr.Attribute1, null, "id=" + #Model.Id + "" )
the id will generate like this
id="id_1", id="id_2" and so on..
<input id="Checkbox1_#(test.TestId)" type="checkbox" />
i hope upper code will help you

Html.DisplayFor in mvc webgrid

Using an asp.net mvc webgrid, is it possible to render a column using Html.DisplayFor for the current row/column?
grid.Column("Roller", "Roller", canSort: true, format: #<text>#Html.DisplayFor( <the row result here> )</text>)
The Html.DisplayFor(m) helper uses the page model, not the current row item. Is there a way around this.
Thanks
// Johan
Yes, it is possible. For an example, consider you are binding a list of Banner objects to your WebGrid. Also consider the Banner.Active property, which is a boolean value that you want to be rendered as a CheckBox. You can do this:
format: (item) => { var banner = item.Value as Banner;
return Html.DisplayFor(modelItem => banner.Active);
}
You could also do this:
format: (item) => Html.DisplayFor(modelItem => ((item as WebGridRow).Value as Banner).Active)
But I would consider the first option more readable.
try this
var grid = new WebGrid(Model);
than do
grid.Column("Roller", "Roller", canSort: true, format: #<text>#Html.DisplayFor(modelItem => item.blabla)</text>)
Using item.blabla"whatever ur item name is" may work but im not really experienced about this.
also there is not much difference between
#<text>#Html.DisplayFor(modelItem => item.blabla)</text>
&
#<text>#item.blabla</text>
both usage does the job.

Reloading an ASP.NET MVC3 Partial View without using AJAX

I have an MVC3 application with Razor and I created a View that inside renders a Partial View. This is how the main View looks like:
#{Html.RenderPartial("_SearchFilters", Model.SearchFilters);}
#* Other HTML elements *#
Inside the _SearchFilters Partial View I have the following DropDownLists inside a Form element:
Choose Year
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text"), DateTime.Now.Year)
Choose Month
#Html.DropDownListFor(m => m.Month, new SelectList(Model.MonthsList, "Value", "Text"), Model.Month.ToString(), new { #disabled = "disabled" })
<input type="submit" value="Display" />
I would like that upon Submit the two DropDownLists keep their status, namely the value selected by the user, when the View is reloaded with the filtered data.
Is there any way to do it without using AJAX?
UPDATE
The ViewModel is as follows:
public class TableSearchFiltersViewModel
{
public bool YTM { get; set; }
public int? Month { get; set; }
public int? Year { get; set; }
public IEnumerable<SelectListItem> YearsList
{
get
{
return Enumerable.Range(2011, (DateTime.Now.Year - 2011 + 4)).Select(m => new SelectListItem
{
Value = m.ToString(),
Text = m.ToString(),
}).OrderBy(m => m.Value);
}
}
public IEnumerable<SelectListItem> MonthsList
{
get
{
return Enumerable.Empty<SelectListItem>();
}
}
}
Thanks
Francesco
When you submit the form to the corresponding controller action, this action should take as input parameter some view model. This view model's properties will be bound from the input fields contained in the form including the selected value of the two dropdowns. Then the controller action could return the same view which will preserve the selected values of the dropdown boxes.
I would recommend you to use Editor Templates though instead of rendering partials as this will ensure proper naming of the dropdowns and eventually preserve selected values:
#Html.EditorFor(x => x.SearchFilters)
I don't have IDE at this time so couldn't test but this might work:
Choose Month
EDIT:
#Html.DropDownListFor(m => m.Month,
Model.MonthsList.Select(
t => new SelectListItem {
Text = t.Name,
Value = t.Value,
Selected = t.Value == Model.Month,
},
Model.Month.ToString(), new { #disabled = "disabled" })
Without ajax not, or you will have to repost the whole form. MVC is a web framework which is not dynamic like a winforms application. You will have to post the changes to your controller and reload the page with the necessary changes, or use ajax to reload these changes.
You could provide the default values for Year and Month properties (to be selected at the first request) and bind those instead of the hardcoded startup values you provided.
So instead of:
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text"), DateTime.Now.Year)
Which btw seems erroneous, as selected value (which I suppose DateTime.Now.Year is in your example) should be provided as SelectList's constructor (instead of DropDownListFor method's) argument. DropDownListFor method doesn't have a 'selected value' argument.
You could write:
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text", Model.Year))
and analogously in the second dropdown.
This will make dropdowns keeps the selected values when rendered using the posted model (as Model.Year and Model.Month would hold those). So you should make sure those values won't get overwritten with default ones after subsequent submits.

Categories