I'm using the code below to create the id for one element in my editor template, is there another way to get a valid id in the editor template?
ViewData.TemplateInfo.HtmlFieldPrefix.Replace('.', '_');
Try like this:
#{
var id = ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty);
}
Related
I can't figure out how to determine which item is selected in the my kendo dropdownlist. My view defines it's model as:
#model KendoApp.Models.SelectorViewModel
The ViewModel is defined as:
public class SelectorViewModel
{
//I want to set this to the selected item in the view
//And use it to set the initial item in the DropDownList
public int EncSelected { get; set; }
//contains the list if items for the DropDownList
//SelectionTypes contains an ID and Description
public IEnumerable<SelectionTypes> ENCTypes
}
and in My view I have:
#(Html.Kendo().DropDownList()
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This DropDownList contains the values I expect but I need to pass the selected value back to my controller when the user clicks the submit button. Everything works fine except I don't have access to which item was selected from the controller's [HttpPost] action. So, how do i assign the DropDownList's value to a hidden form field so it will be available to the controller?
For anyone who found this wondering how to get the selected value in JavaScript, this is the correct answer:
$("#EncounterTypes").data("kendoDropDownList").value();
From the documentation: http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#methods-value
when select a value from a dropdown list, and in the selec event , we can get the selected value as following ,
#(Html.Kendo().DropDownList()
.Name("booksDropDown")
.HtmlAttributes(new { style = "width:37%" })
.DataTextField("BookName")
.DataValueField("BookId")
.Events(x => x.Select("onSelectBookValue"))
.DataSource(datasource => datasource.Read(action => action.Action("ReadBookDropDow", "PlanningBook").Type(HttpVerbs.Get)))
.OptionLabel("Select"))
javascript function like following ,
function onSelectBookValue(e) {
var dataItem = this.dataItem(e.item.index());
var bookId = dataItem.BookId;
//other user code
}
I believe this will help someone
Thanks
Hello I was just going through this problem,kept on searching for 2 hours and came up with a solution of my own.
So here is the line to fetch any data bidden to the kendo drop down.
$("#customers").data("kendoDropDownList").dataSource._data[$("#customers").data("kendoDropDownList").selectedIndex].colour;
Just change the id customers to the id you have given tot he kendo drop down.
Maybe you should be using the DropDownListFor construct of the Kendo DropDownList like so in your view:
#(Html.Kendo().DropDownListFor(m => m.EncSelected)
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This way, when you submit, it will be availble on the POST request and you won't need to put an hidden field anywhere.
BUT should you need to use the hidden field for some reason, put it there, subscribe the the select event of the dropdown list and put using JQuery (for instance) put the selected item on the hidden field.
It's your choice :)
If you want to read also out the text of the dropdown, you can get or set the value by using the following kendo function:
$('#EncounterTypes').data("kendoDropDownList").text();
REFERENCE TO THE DOCUMENTATION
Using this .val() as #Vivek Parekh mentions will not work - there is no function .val() in the kendo framework.
If you want you could use jQuery and get the value back: $('#EncounterTypes').val()
Updated DEMO
$("#EncounterTypes").kendoDropDownList().val();
You can get the selected item like following code and then use item.property to get further information
var selectedFooType = $("#fooType").data("kendoDropDownList").dataItem();
selectedFooType.name
//OR
selectedFooType.id
Hi Folks i am retrieving Name from database to drop down list. Now i want to display the selected value from DropDown in a page. My code is like follows to retrieve data,am using Fluent data as a framework.
My Controller Action is
var query = Abc.GetProducts();
ViewBag.EnterpriseId = new SelectList(query.AsEnumerable(), "EnterpriseId", "Name");
return View();
My view is ,
#Html.DropDownList("EnterpriseID", (SelectList) ViewBag.EnterpriseID, "--Select Resource--")
You can use a simple js for this:
elem = $('.selectClass');
options = elem.find('option[value="'+DataFromDBHere+'"]');
if(options){
options.prop('selected', 'selected');
}
I've two tables
1.Country
ID
CountryName
and other table is
2.State
State ID
State Name
Country Id
I am using this code to populate data in dropdownlist of country in citycontroller.cs
ViewBag.countries = new SelectList(db.Couns.OrderBy(c => c.CountryName).ToList(), "ID", "CountryName");
in create.cshtml
#Html.DropDownList("Select Country", ViewBag.countries as SelectList)
i want the functionality in which the state dropdown should be populated according to the selection of the country dropdown what should be done?????
If you have the list of states downloaded already to the client machine then knockout.js would be the way to go. If you want to download only the states that are related to the selected country once that selection is made you shohuld make an AJAX call to the server when a country is selected and have the success function populate the state list.
You will need to use Ajax calls for that. You may want to have a look at this answer I provided to a question similar to yours.
You can wse jQuery ajax to load the States when the country gets selected.
<script type="text/javascript">
$(function(){
$("#Country").change(function(){
var states="";
var countryId=$(this).val();
$.getJSON("#Url.Action("GetStates","Home")/"+countryId,function(data){
$.each(data,function(index,item){
states+="<option value='"+item.ID+"'>"+item.StateName+"</option>";
});
$("#States").html(states);
});
});
});
</script>
Assuming Country is the ID of your Country DropDown and States is the ID of your States Dropdow and you have an action method which accepts the country id as the parameter and get the states in JSON format
public ActionResult GetStates(int id)
{
var stateList=repo.GetStatesForCountry(id);
return Json(stateList,JsonRequestBehaviour.AllowGet);
}
Assuming repo.GetStatesForCountry returns a List of States based on the country Id passed. You may replace that function call with your method call which returns a list of State class objects.
Suggestion : I would try to avoid the dynamic ViewBag /ViewData approach to populate the Dropdwon and switch to a more strongly typed approach. Here is an example how to do it.
I have following code
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), Model.SelectedID)
}
So user selection from this combo bind to SelectedID property of the model. My understanding is that this binding happen only when form is submitted. Let’s say from the same page, I need to do an AJAX call but at this point ) Model.SelectedID does not provide any value because form hasn’t been submitted yet (although user has selected something from drop down). Any ideas how to best deal with this situation?
You can use javascript.
var selectedValue = $("#IDs").val();
bind a change event to your DD
$("#DDL_ID").change(function(){
var currVal = $(this).val();
//do ajax
});
As others have pointed you would get this value with javascript on the change of the drop down list.
I wanted to point out however, that your understanding of the overload you are using for the drop down list is incorrect. This overload will display a default option box label.
For example you could prompt the users to select select something from the list:
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), "Select Something...")
If you were to post the form in your example as is, you can see the selected item come across in the form. If your view model is setup in such a fashion the model binder would take over and bind this value to your "SelectedID" property.
[HttpPost]
public string DropDown(FormCollection form)
{
var selectedItem = form["IDs"];
return selectedItem;
}
After selecting an accountholder I want to prepopulate my Order Create View with the properties of the selected accountholder.
My Controller Action so far:
[HttpPost]
public ActionResult Create(FormCollection values)
{
var accountHolder = from a in unitOfWork.AccountHolderRepository.Get(includeProperties: "AccountHolder")
where a.CustSName == values["Name"]
select a;
foreach (var a in accountHolder)
{
ViewBag.CustFName = a.CustFName;
ViewBag.CustSName = values["Name"];
ViewBag.CustPhone = a.CustPhone;
ViewBag.CustEmail = a.CustEmail;
}
return RedirectToAction("Create", "Order");
}
Not sure if I understand correctly what are you trying to accomplish here. I'm assuming :
Displaying Empty Create form
User provides value for AccountHolder (automatic submit happens?)
You return pre-populated form
Final Create step to preserve values to database
Am I right ?
If so, instantiate the model / viewmodel you're using in your create form (you're using strongly typed view right ?) and return it like this :
return View(yourobject); //Assuming the first view returned by GET request to Create action has all the properties in place
however that should happen only if the values are missing, right. so you might want to add some more logic to your controller to verify if pre-popullation or db.Save() is required.
As you're calling RedirectToAction to the Order controller, I assume you are now in the Create method of the accountholderController?
What's your question exactly? Without specifics, I can't give you much help.
Some notes though:
Try to search for the accountholder based on its ID in the database rather than the name. You are now trusting your enduser to enter the accountholder name exactly as it is entered in the database (same case, same punctuation). ID's are more precise and require less effort to get right.
Why use the Post-Create method if all you want to do is select an accountholder from a list and then open a Create view? It would be much wiser to have a dropdownlist containing all accountholders on your main page (or wherever you want to put it). something along the lines of
<select name="accountholderID">
<option value:"ID_of_accountholder">Name_of_accountholder</option>
...
</select>
Add a button next to that. Once an accountholder is selected and the button is clicked, call your (Get, not Post) Create method in the OrderController. Pass the accountholderID as a parameter. Your Create methoud should be something like:
public ActionResult Create(string accountholderID)
{
int ID = Convert.ToInt32(accountholderID);
ViewData["Accountholder"] = database.tbl_Accountholders.SingleorDefault(x=> x.Id == ID);
...
And in your Create View just access the values of your accountholder like so:
<% var accountholder = (accountholdertype)ViewData["Accountholder"]; %>
<span> Name is <%: accountholder.Name %> </span>
I think that should get you where you want to be :-)