Kendo Ui dropdownlist with ASP.NET MVC5 onSelect function - asp.net-mvc

I am using Kendo UI Dropdownlist with ASP.NET MVC5.
I want to write a cookie onSelect:
#(Html.Kendo().DropDownList().Name("sss").BindTo(Model).DataTextField("Name").DataValueField("Id")
.Events(e =>
{
e.Select("onSelect");
})
.Deferred()
)
function onSelect(e) {
if ("sss" in window) {
debugger;
var dataItem = this.dataItem(e.item);
alert(dataItem.value);
setCookie(dataItem.value);
}
}
all the functions are reachable and working fine. but I am getting an:
undefined
value instead of Id.
why am I receiving this error? and how can I fix it?
P.S. the Model contain both Id and Name.

Once you get the dataItem, it is an instance of your model used to populate the DropDownList.
So, in order to access the Id field, use the Id field not the value field(which your model does not have).
function onSelect(e) {
if ("sss" in window) {
debugger;
var dataItem = this.dataItem(e.item);
alert(dataItem.Id);
setCookie(dataItem.Id);
}
}

Related

Kendo control value in the event is the controls previous value

I am trying to understand why this isn't working. If i set the value of myTextBox to 5 then trigger the change event. the value for my myTextBox is null. If i change the value to 10 then fire the event again, the value will be the previous one (5). I've compared it to one of the many textboxes working on the form and they appear the same. The only difference is the value property in the wrapper object is set in the ones that work but behind in the one that doesn't. Digging into the both objects element property, i see the values are correct and current. Any help would be appreciated.
Model Property
[UIHint("Decimal")]
[Display(Name = "Example")]
public decimal? MyTxt{ get; set; }
Template (Decimal.cshtml):
#model decimal?
#{
var defaultHtmlAttributesObject = new { style = "width:100%" };
var htmlAttributesObject = ViewData["htmlAttributes"] ?? new { };
var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesObject, defaultHtmlAttributesObject);
}
#(Html.Kendo().NumericTextBoxFor(m => m)
.Format("#.00")
.HtmlAttributes(htmlAttributes)
)
UI Declaration
#Html.EditorFor(m => m.MyTxt, new { htmlAttributes = new { #style="width: 100%", #readonly = "readonly" } })
Javascript:
var myTextBox = $('#MyTxt').data('kendoNumericTextBox');
$(document).on('change', '#foo', function(){
var test = myTextBox.value();
})
Update:
In the document ready function i was binding the change event like this:
$('#MyTxt').change({ source: $('#MyTxt'), destination: someObject, isTwoMan: true, crewType: LaborType.Set }, SomeCalcFunction);
The jQuery change event fires nefore the kendo one thus the delay in getting the correct value. The fix was to read the manual and bind to the event the kendo way
the issue was in the way i was binding to the change event.
$('#MyTxt').change({ source: $('#MyTxt'), destination: someObject, isTwoMan: true, crewType: LaborType.Set }, SomeCalcFunction);
will fire before the kendo event does. Changing it the kendo way fixed my issue
$("#MyTxt").bind("change", function (e) {
var event = jQuery.Event('change', {
source: $("#MyTxt"),
destination: someObject,
isTwoMan: true,
crewType: LaborType.Set
});
SomeCalcFunction(event);
});

can't get the data Kendo pager

I'm trying to use kendo pager in my project but I can't get the data see the attached image
[result][1]
[1]: http://i.stack.imgur.com/xmLYn.png
here is my javascript code :
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Option/Get',
}
},
pageSize: 2,
schema: {
data: 'Data',
model: { id: 'ID' }
}
});
the action method :
public JsonResult Get([DataSourceRequest] DataSourceRequest request,int Id)
{
var donnees=_DService.GetList(Id);
var results = donnees.ToDataSourceResult(request);
return Json(results);
}
The problem is caused by the missing schema.total setting. Since you are using ToDataSourceResult, then it should be set to "Total".
In addition, the action method expects an Id parameter, which the Kendo UI DataSource currently does not provide. If you need this parameter to query the database, then use the data function of transport.read to send it.
Last but not least, call the fetch method of the Kendo UI DataSource instance, unless there is some other widget that will do that automatically (e.g. a ListView).
Here is an example, compare it with your implementation:
http://dojo.telerik.com/okaTeD
This is the dummy data service:
http://dojo.telerik.com/ifEvu

How to create a dynamic dropdown in mvc

How to create a dropdown whose option values are coming from controller.
controller will be getting it from database table's any column value.
for example if that dropdown is for selecting country, and i have 3 country in my database table's country column, in dropdown it should show the 3 country. And if I add one more value in country table, that also should come in dropdown.
I am new to MVC an this is found bit difficult. I am using mvc5.
NB: since I already one model is refered inside the view, I cant add the model for this dropdown
I have done the same in my own website. This is how I do it:
Firstly, create a action for controller which returns JSON value:
public ActionResult GetCountryNames()
{
List<string> CountryNames = new List<string>();
CountryNames = context.GetCountries(); // your EF context to get countrynames from database
return Json(CountryNames.ToArray());
}
Then in your view add this html mark up:
<select id="countrylist" onchange="DoSomething();"></select>
This is your dropdownlist. It has javascript function declared in "onchange" event, if you want to do something when value changes.
Lastly, you need to add your javascript function, which does ajax call to your controller action, gets values and set it to your dropdownlist:
function GetCountryList() {
var serviceURL = '/Home/GetCountryNames';
$.ajax({
type: "post",
dataType: "json",
url: serviceURL,
success: successFunc,
async: false,
error: errorFunc
});
function successFunc(data, status) {
var countrylist = $('#countrylist');
countrylist.empty();
for (var i = 0; i < data.length; i++) {
var $option = $("<option>", { id: "option" + i });
$option.append(data[i]);
countrylist.append($option);
}
}
function errorFunc(data, status) {
alert('error');
}
}
And when your document is ready, run function GetCountryList().
Probably easiest is to do it with jQuery. Like this:
<script type="text/javascript">
$(document).ready(function () {
GetCountryList();
});
</script>

How to Prevent Page refresh on select change for dropdownlist in MVC

I have a dropdownlist in my razor view MVC like
#Html.DropDownListFor(n => n.EMP_ID, (SelectList)ViewBag.EmployeeList, new { #id = "ddlemployee" },"---choose an Employee Name--").
I have applied select change event to drop-down using jquery, when select Employee name getting Employee names and realted data, but problem is when i select a value in drop-down, dropdownlist setting again set to default first value,
It is not sticking to particular selected value, in terms of Asp.net terminology, how to prevent postback to dropdownlist?
//Redirected to Controller
<script>
$(document).ready(function () {
$("#ddlemployee").change(function () {
location.href ='#Url.Action("GetEmployeeDetails", "Employer")'
});
});
</script>
//Action Method in Employer Controller
public ActionResult GetEmployeeDetails(Timesheetmodel model)
{
try
{
ViewBag.EmployeeList = objts.getEmployeeNames();
var emps = from n in db.TIMESHEETs
where n.RES_ID == model.EMP_ID
select n;
int count = emps.Count();
foreach (TIMESHEET ts in emps)
{
model.PROJ_ID = ts.PROJ_ID;
model.SUN_HRS = ts.SUN_HRS;
model.MON_HRS = ts.MON_HRS;
model.TUE_HRS = ts.TUE_HRS;
model.WED_HRS = ts.WED_HRS;
model.THU_HRS = ts.THU_HRS;
model.FRI_HRS = ts.FRI_HRS;
model.SAT_HRS = ts.SAT_HRS;
}
}
catch (Exception ex)
{
throw ex;
}
return View("Timesheet", model);
}
ASP.Net Webforms achieve StateFullness by using Some thing called ViewState
It is implemented as hidden fields in the page to hold data between requests.
This way , asp.net webforms achieves post back mechanism and was able to hold values in bewteen the requests.
Since Http is a stateless protocol , which means it has no relation between requests.
View State is absent in ASP.Net MVC.
So, you have to stop postback by partially posting back . Which means that you need to send an asynchronous request with out refreshing whole page.
It is possible by using AJAX. You can either use
MVC Ajax or Jquery Ajax.
By using AJax, we can eliminate the post back and then do the partial post back.
Solution:
$("#dropdownid").change(function(event e)
{
//Make your ajax request here..
});
Hope this helps
Updated:
$("#dropdownid").change(function () {
$.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
url: /*Your URL*/,
success: function (data) {
//do your callback operation
}
});
});
Got it.
Passing Empid as querystring from jquery like:
<script>
$(document).ready(function () {
$("#ddlemployee").change(function () {
debugger;
var empid = $("#ddlemployee").val();
location.href = '#Url.Action("GetEmployeeDetails", "Employer")?empid=' + empid ;
});
});
</script>
and assign "empid " to model "Empid" in Action method before foreach loop like
model.EMP_ID = empid;//in Controller Action Method before foreachloop of my code
// and this model.EMP_ID binded to dropdownlist.
this EMP_ID passes same id to dropdownlist which was selected. Thats it.

ASP MVC3 - Make second call to controller once jQuery autocomplete value selected

Below are the jQuery versions that I am referencing in my ASP MVC view
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
Using the autocomplete widget, I would like the form to fill out a separate text box based on the user's selection from the autocomplete list. On this page, the user will begin typing a bank name. Once the user selects which bank they need, another field by the name of Dynamics ID needs to be populated with the appropriate value. Here is the jQuery as it's written right now
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1,
onComplete: function (data) {
$.getJSON('#Url.Action("GetDynamicsId", "AgentTransmission")', data, function (result) {
$('Dynamics').val(result);
})
}
});
});
And here are the two controller methods that are called in the above jQuery
//GET
public JsonResult GetBanks(string term)
{
var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(term))
select c.BankName;
banks = banks.Distinct();
return Json(banks, JsonRequestBehavior.AllowGet);
}
//GET
public JsonResult GetDynamicsId(string term)
{
var dynamics = from c in db.BankListMaster.Where(n => n.BankName.Equals(term))
select c.LinkRepsToDynamicsUniqueId;
dynamics = dynamics.Distinct();
return Json(dynamics, JsonRequestBehavior.AllowGet);
}
Once the user has made a selection from the list, I wanted to be able to send back the ID value to that bank. That serves as the primary key for the BankListMaster table, of which BankName and DynamicsId are both fields. I'm still new to jQuery, however, so I may not be able to do this.
Right now, I've set a breakpoint in the first line of both controller methods. The GetBanks breakpoint fires everytime, however I cannot get the GetDynamicsId to fire at all.
EDIT
Since I'm only selecting the BankName field in the first query, I adjusted the GetDynamicsId method to use the bank name as the parameter.
I do something similar by handling the "select" event. It's not "onComplete" as you had in your example. Your code with this change would be:
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1,
select: function (event, ui) {
$.getJSON('#Url.Action("GetDynamicsId", "AgentTransmission")', { term: ui.item.value }, function (result) {
$('Dynamics').val(result);
})
}
});
});

Resources