DataValueField Missing in kendo Autocomplete - c#

I am using kendo autocomplete control in my MVC project(Server side filtering).It list the data correctly. But the problem is when i submit the data to server the autocomplete value id is missing. Because there is no DataValueField attribute in this control. The bellow code is i am using
#(Html.Kendo().AutoComplete()
.Name("Patient")
.Placeholder("Enter Name")
.DataTextField("TextField")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("function", "controller")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
How can i send the value to the server.
Thank you..

Since AutoComplete helper doesn't have DataValueField attribute, you need to use other HTML helper as workaround to pass another property value. Suppose your viewmodel has this setup:
public class ViewModel
{
// ID property example
public int PatientID { get; set; }
// other properties
}
You can create a hidden field or read-only textbox to store ID property mentioned above inside Razor view:
#Html.HiddenFor(m => m.PatientID)
Then, assign its value attribute from client-side script by creating a function which reads item index from autocomplete helper:
function selectPatient(e) {
var item = this.dataItem(e.item.index());
$('#PatientID').val(item.PatientID);
}
And finally set the function name bound for Events attribute:
#(Html.Kendo().AutoComplete()
.Name("Patient")
.Placeholder("Enter Name")
.DataTextField("TextField")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
// add this line
.Events(ev => ev.Select("selectPatient"))
.DataSource(source => {
source.Read(read => {
read.Action("function", "controller")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
By following this setup, the PatientID property should have ID of the selected value from autocomplete helper when user submitted the form.

This is a known limitation of the AutoComplete widget. One way around it is to add an attribute via a template to store the data value on the control:
#(Html.Kendo().AutoComplete()
.Name("Patient")
.Placeholder("Enter Name")
.DataTextField("TextField")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("function", "controller").Data("onAdditionalData");
})
.ServerFiltering(true);
})
.Events(events => events.Select("onPatientSelected"))
.Template("<span data-recordid=\"#= data.ID #\"> #: data.ID # – #: data.Name #</span>")
)
This assumes ID and Name are properties of the patient object.
Then you can handle the Select event to get the stored ID value when a selection is made:
function onPatientSelected(arg) {
var selectedPatientID = arg.item.find('span').data('recordid')
// do whatever with the ID, such as sending it to the server
}

You can access the dataItem in javascript, and then access the value property.
If you call myKendoAutoCompleteControl.dataItem() it will give you the currently selected item as an array of key/value pairs.
$("#myKendoAutoCompleteId").kendoAutoComplete({
dataTextField: "Text",
dataValueField: "Value",
dataSource: mydatasource,
filter: "startswith",
placeholder: "Search..."
//separator: ", "
});
var myKendoAutoCompleteControl =
$("#myKendoAutoCompleteId").data("kendoAutoComplete");
// once user has selected an item in the kendo auto complete control, you
can access the selected item.
var dataItemArray = myKendoAutoCompleteControl.dataItem();
var value = dataItemArray.Value

Related

Objects not coming through for Kendo MVC Autocomplete UI

I had this working at one point but I'm not sure what is breaking it now. Objects and object properties are not populating the drop down. I can get object properties to show up if I pass just an array of strings of one of the properties in my autocomplete controller but I would like to pass the whole objects to the autocomplete dropdown and style a template from there. I have been changing DataTextField and Template to simplify for this example and testing purposes but hasn't granted any success yet. Also now I am returning an array of Objects from my Parts_Read method and made sure that AllowGet was enabled. Do you notice anything I am missing?
View
#(Html.Kendo().AutoComplete()
.Name("parts_results")
.DataTextField("Name")
.Template("#= VendorPartCode # | #= Name # | #= UpcCode #")
.HeaderTemplate("<div class=\"dropdown-header k-widget k-header\">" +
"<span>Matching Parts</span>" +
"</div>")
.FooterTemplate("Total <strong>#: instance.dataSource.total() #</strong> items found")
.Filter("contains")
.MinLength(3)
.HtmlAttributes(new { style = "width:100%", #class = "form-control"})
.Height(520)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Parts_Read", "AutoComplete")
.Data("onAdditionalData");
})
.ServerFiltering(true);
})
)
Script
function onAdditionalData() {
return {
text: $("#parts_results").val(),
supplier: $("#part_supplier").val()
};
}
Autocomplete controller
public JsonResult Parts_Read(string text)
{
int supplier = int.Parse(Request.Params["supplier"]);
var search = Request.Params["text"];
if (!string.IsNullOrEmpty(text) && supplier >0)
{
dbContext db = new dbContext();
var data = db.dbParts.Where(x => x.PartSupplierCompanyId == supplier && (x.PartName.ToLower().Contains(search.ToLower()) || x.PartCode.ToLower().Contains(search.ToLower()))).Select(p => new TimsPart(p,p.Company)).ToArray();
return Json ( data, JsonRequestBehavior.AllowGet );
}
else
{
return new JsonResult { Data = new List<TimsPart>(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}

How to take value from DataValueField() of a Kendo().DropDownList() on change event

I'm using kendo grid and editor template for showing my data. in editor I've given id to DataValueField() and name to DataTextField() of kendo dropdown list. In change event, I'm not able to get the DataValueField(). see the following code
This is my editor template MemoCarrier.chtml
#using System.Collections
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
.Events(e =>
{
e.Change("MemoCarrier");
})
)
Here is my on change function
function MemoCarrier(e) {
var AirlineName = this.value();
alert(AirlineName) //it displays PARTNERNAME instead of PARTNERID
}
Currently I'm getting name ie;DataTextField() value. instead of that, I need DataValueField().
Thanks for suggestions in advance!
so based on your comment the easiest way to do this would probably use the data-bind attribute to simplify the process of binding the model. Assuming you are using the MVC helper for the grid as well.
so taking your code and adding this:
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum", data_bind="value:{yourProperyNameHere}" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
)
So hopefully you can see all I am doing is adding a new HtmlAttribute property to the control for you. All you need to do is put whatever property is meant to be the value for this.
Depending on if this value is a complex (object) or simple (string, int etc) primitive type you may need to set the Primitive property to true so that only the valuefield e.g the id you are assigning is bound back to the grid's row model.

Asp.Net MVC Get value from Dropdownlist to PartialView

In my main page I have Dropdownlist of Cars. And it works fine.
And When I select one car from Dropdownlist I want to get back all car modells who belongs to the selected Car from Dropdownlist in the same view, let say under Dropdownlist. DropDownlist with Cars and Models of the selected cars in the same View (in Main view). I tried with PartialView but I'am not so good when it comes PartielView and html code
This is my action to get CarModels, and I think this must be as PartialView
[HttpGet]
public ActionResult GetCarModel(int? carId)
{
List<CarModelVW> listOfCarModel;
using (Db db = new Db())
{
listOfCarModel = db.CarModel.ToArray()
.Where(x => carId == null || carId == 0 || x.carId == carId)
.Select(x => new CarModelVW(x))
.ToList();
}
return View(listOfCarModel);
}
In my Main View with DropDownlist
<div class="form-group">
<label class="control-label col-md-2" for="HasSidebar"> Car </label>
<div class="col-md-10">
#Html.DropDownListFor(model => model.CarId, Model.Cars, "---Select car---", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CarId, "", new { #class = "text-danger" })
</div>
</div>
And here below Dropdownlist I want to get all carmodels of selected car
But I think I have to create <div> </div> with Id or span .. but I'am not sure how to do here.
And here is javascript I'am trying to use
$("#CarId").change(function () {
var carId = $(this).val();
if (carId) {
window.location = "/an/GetCarModel?carId=" + carId;
}
return false;
});
How do I get this action GetCarModel below Dropdownlist view? Thank you in advance.
Just like Roman said, instead of navigating to the url, you should send an ajax call to the control.
First of all, add an id to your dropdownlist.
Secondly, in the Onchange function add an ajax call to get cars:
var dropdownval = $("#//Id of dropdown").val();
var json = '{Id: ' + dropdownval + '}';
$.ajax({
url:'#Url.Action("GetCarModel", "//The controller")',
type:'POST',
data: json,
contentType:'Application/json',
success:function(result){
//Do whatever
}
})
You can then do whatever with the result you pass back to the ajax call
If you want to view results on the same page then you need to use Ajax.
add this div tag Main view where you want to display results:
<div id="carmodels"></div>
Change your jquery function as below:
$("#CarId").change(function () {
var carId = $(this).val();
if (carId)
{
$.get("/an/GetCarModel?carId=" + carId, function(data){
$("#carmodels").html(data);
});
}
});

MultiLineText DataType Value not populating in TextAreaFor

I am attempting to implement an Update on a current text area value.
The datatype is set for multiline in my model
[DataType(DataType.MultilineText)]
public string Text { get; set; }
When the page loads for the textarea, it does not populate.
#Html.TextAreaFor(a => a.Text, new { #Value = Model.Text })
But for a textbox it does populate
#Html.TextBoxFor(a => a.Text, new { #Value = Model.Text })
Is there something I'm missing? this seems pretty straight forward.
#Html.TextAreaFor(a => a.Text, new { id = "SomeID", placeholder = "Text", Value = Model.Text})
#Html.TextAreaFor(m => m.UserName) should be enough - ASP MVC takes care of populate current value from model to textarea.
Using { #Value = Model.Text } doesn't apply to textarea as it does not uses value attribute: How to add default value for html <textarea>?

How to update KendoGrid from combobox

I'm writing a web app in ASP.NET MVC using Kendo UI. I'm visualizing data in a Kendo Grid as follows:
#(Html.Kendo().Grid<MyModel>()
.Name("grid")
.DataSource(dataSource => dataSource // Configure the grid data source
.Ajax() // Specify that ajax binding is used
.Read(read => read.Action("ReadAction", "MyController", new { /*route values*/ }))
)
.Columns(columns =>
{
columns.Bound(n => n.Month).Title("Month").ClientTemplate("<input type='hidden' value='#=Month#' id='hfMonth'/>").Hidden();
columns.AutoGenerate(true);
})
.Pageable()
.Sortable()
Now I need to fire an update of the grid based on the change event of a <select>. How can I do this? I'm trying several possibilities from yesterday, with no success as all.
Without seeing your code for the combobox I would do the following:
View
#(Html.Kendo().ComboBox()
.Name("combo")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Foo", Value = "1"
},
new SelectListItem() {
Text = "Bar", Value = "2"
},
new SelectListItem() {
Text = "Baz", Value = "3"
}
})
.Events(events =>
{
events.Change("onChange");
})
)
JavaScript
function onChange(e) {
var grid = $("#grid").data("kendoGrid");
// if the selected value is not needed
grid.dataSource.read();
// if the selected value is needed use below instead
// changing the route parameter to match yours
var selectedValue = this.Value();
grid.dataSource.read({ id : selectedValue });
}
Update
As per #PierpaoloIlConteParis comments:
I didn't specify directly the parameters in the read.Action method, but instead I used the handler function like in this post telerik.com/forums/… Now when changing the combobox value the action fires with right parameters

Categories

Resources