ASP.NET Telerik combobox is not being updated with new values - c#

I have an ASP.NET MVC application which uses Telerik controls. I am new in Telerik controls.
In my asp.net view (.cshtml) I have below Telerik combobox defined:
<div class="inline-form-field">
<label>#Ubicaciones.lblTipoVia.ToUpper()</label>
#(Html.Telerik().DropDownListFor(t => t.tipoViaId)
.BindTo(new SelectList(#ViewBag.tiposVia, "tipoViaId", "descripcion"))
.HtmlAttributes(new { style = "width: 190px;" })
)
</div>
Later in the same view, when a condition is satisfied I call below below javascript function in order to update the combox with new values coming from a function in ASP.NET MVC controller:
function cargarTiposVia(){
var comboTiposVia = $('#tipoViaId').data('tDropDownList').value();
var actionUrl = '#Url.Action("GetTiposVia", "Ubicaciones")?municipioId=' + $('#codigoMunicipio').val() + '&localidadId=' + $('#codigoLocalidad').val() ;
$.ajax({
url: actionUrl,
async:false,
type: "POST",
traditional: true,
success: function (data) {
if (data)
{
comboTiposVia.dataBind(data);
}
}
});
}
Below the function GetTiposVia in the ASP.NET MVC Controller:
public JsonResult GetTiposVia(string municipioId, string localidadId)
{
CommonManager commonManager = new CommonManager(currentUserSociedadId);
List<My.DTOs.TipoViaDTO> tiposVia = commonManager.getTiposViaByMunicipio(municipioId);
//ViewBag.tiposVia = tiposVia;
return Json(new SelectList(tiposVia, "tipoViaId", "descripcion"), JsonRequestBehavior.AllowGet);
}
Ajax result is success (I have checked by putting an alert), so comboTiposVia.dataBind(data) is executed but combox is not loaded with the new values. I do not understand what is happening...

I have solved. The problem was I was taken the current item selected value in the combobox and not the combobox instance.
Changing:
var comboTiposVia = $('#tipoViaId').data('tDropDownList').value();
by
var comboTiposVia = $('#tipoViaId').data('tDropDownList');
is working.

Related

How to convert Kendo dropdownlist into Kendo multiselect

I am converting Kendo dropdownlist from the existing code into Kendo multiselect.
Role Code: Currently Dropdownlist (converting to Kendo multiselect).
I am not getting the correct output.
I have the following code:
<div class="col-md-4 form-group">
#Html.LabelFor(model => model.RoleCode, htmlAttributes: new { }) <span style="color: Red">*</span>
<select id="DDRolecode" multiple="multiple" data-placeholder="Select attendees...">
</select>
</div>
...
...
var url = '#Url.Action("GetRoleCode", "FlowGenerator")';
url = url + '?FlowID=' + flowid + '&RegID=' + RegId;
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
success: function (result) {
debugger;
//$("#DDRolecode").kendoDropDownList({
// dataTextField: "Name",
// dataValueField: "ID",
// optionLabel: "Select",
// dataSource: result
//});
$("#DDRolecode").kendoMultiSelect({
dataTextField: "Name",
dataValueField: "ID",
dataSource: result,
});
var selectedData = [];
for (var i = 0; i < result.length; i++) {
selectedData.push({
text: result[i].Name,
value: result[i].ID
})
}
DDRoleCode.dataSource.data(selectedData);
//DDRoleCode.setDataSource(selectedData);
DDRoleCode.value('');
DDRoleCode.enable(true);
},
error: function (data) {
debugger;
var itemRow = "<ul id='listError'><li>" + "Data Not Bind" + "</li></ul>";
FUNMessageBox(itemRow, "E", 0, 0, "", "");
// alert("error");
}
});
The below is the controller code where I am getting the role codes:
public JsonResult GetRoleCode(int FlowID,int RegID)
{
IEnumerable<GenericValues1> RoleCode = _repository.Context.Database.SqlQuery<GenericValues1>("PROC_GET_ROLECODE #DATA_FLOW_ID={0},#REG_ID={1}", FlowID, RegID).ToList().AsQueryable();
// ViewBag.Tariffs = RoleCode;
return Json(RoleCode, JsonRequestBehavior.AllowGet);
}
As you can see, I tried using the multiselect functionality in the above code. But it didn't work.
To avoid the long comment chain.
From the second image you have provided it looks like the issue of multiple multiselects being added to the same item. This is due to you attaching a a new multiselect control to the same input.
this is a simple fix really.
There are two ways to fix it.
1) Destroy the kendo widget and recreate it
2) Assuming the same structure is used in the underlying datasource and other settings just apply the new datasource data to the widget.
Here is a dojo showing you both examples:
https://dojo.telerik.com/UxetijUy/2
Personally I would go with option 2 as it is a cleaner solution and avoids having to constantly destroy and recreate widgets.
So if you change the required person in the second example it will take a random number of people from the data array for the multiselect and then rebind those options to that control.
So that is all you would have to do with your ajax call is once you have the result just apply the new data to the datasource and then you don't need to keep recreating the widget as you are currently doing.
So in your example:
$("#DDRolecode").data('kendoMultiSelect').value(null);
$("#DDRolecode").data('kendoMultiSelect').dataSource.data(selectedData);
This ensures you have cleared off any selected items before you have attached the new data source.
If you need more info on what is happening. Please ask and I will update my answer accordingly.
The below code worked for me:
$(document).ready(function () {
debugger;
$("#DDRolecode").kendoMultiSelect({
dataTextField: "Name",
dataValueField: "ID",
});
....
....
//go to controller and call Sp and get the result
success: function (result) {
debugger;
var multiSelect = $('#DDRolecode').data("kendoMultiSelect");
multiSelect.value([]);
$("#DDRolecode").data("kendoMultiSelect").setDataSource(new kendo.data.DataSource({ data: result }));
var selectedData = [];
for (var i = 0; i < result.length; i++) {
selectedData.push({
Text: result[i].Name,
Value: result[i].ID
})
}

Posting AJAX string to MVC Controller

I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).
Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).
Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).
I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)
Controller:
[Authorize]
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
using (CBREntities2 dc = new CBREntities2())
{
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
AJAX function (on View page):
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var yarp = $(this).attr('safesel');
var selectedSafeZZ = JSON.stringify("SEC-1000");
$.ajax({
url: '/Home/GetSafeItems',
data: { 'yarp': JSON.stringify(yarp) },
type: "GET",
success: function (data) {
alert(yarp);
console.log("We WIN " + data)
},
error: function (xhr) {
alert("Boohooo");
}
});
})
** The Alert reveals the correct type: "SEC-1000"
But the console Log shows: WE WIN [Object object]??
I have tried something basic in a new mvc dummy project :
View page basic textbox and a button :
<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>
<script type="text/javascript">
function test()
{
var text = $("#txt_test")[0].value;
$.ajax({
url: '#Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
// edit
// data: {yarp: JSON.stringify(text)},
data: {yarp: text},
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
// edit
// alert(JSON.stringify(data));
alert(data.data);
}});
}
</script>
Controller :
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
return Json(new {data = string.Format("Back end return : {0}",yarp)}
, JsonRequestBehavior.AllowGet);
}
Alert result => {"data":"Back end return : \"test\""}
It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call
Try this:
$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});

Bind the record to html.dropdownlist using ajax call in mvc

I have one Mvc application. In that application in one View i have 2 #html.dropdownlists.I create one function in <script/> tag, will call at selectedIdnexchange event of first dropdown, and get the selected value and send to controller using ajax call. Controller will return result and trying to bind that result with 2nd dropdown.I want to display all RTO names of selected state in 2nd dropdown.
Here is my dropdown
#Html.DropDownList("State", new List<SelectListItem> {
new SelectListItem{Text="Andaman and Nicobar Islands",Value="Andaman and Nicobar Islands"},
new SelectListItem{Text="Andhra Pradesh",Value="Andhra Pradesh"},
new SelectListItem{Text="Arunachal Pradesh",Value="Arunachal Pradesh"},
new SelectListItem{Text="Assam",Value="Assam"},
new SelectListItem{Text="Bihar",Value="Bihar"},
new SelectListItem{Text="Chandigarh",Value="Chandigarh"},
new SelectListItem{Text="Chhattisgarh",Value="Chhattisgarh"},
new SelectListItem{Text="Dadra and Nagar Haveli",Value="Dadra and Nagar Haveli"},
new SelectListItem{Text="Daman and Diu",Value="Daman and Diu"},
new SelectListItem{Text="National Capital Territory of Delhi",Value="National Capital Territory of Delhi"},
new SelectListItem{Text="Goa",Value="Goa"} }, null, new { #class="ddlHtml form-control",#id="ddlState"})
#Html.DropDownList("RTOListItem", new List<SelectListItem> {
new SelectListItem{Text="None",Value="-1"}
}, null, new { #class = "ddlHtml form-control", #id = "DDlforLocations" })
Here is my script function
$(document).on('change', '#ddlState', function () {
var v = document.getElementById("ddlState");
var statevalue = v.options[v.selectedIndex].text;
alert(statevalue);
var j = v.selectedIndex;
if (j == 0) {
sweetAlert("Oops..", "choose correct State", "error");
}
else {
$.ajax({
url: '#Url.Action("GetLocations","Home")',
type: 'GET',
datatype: 'json',
data: { selectedState: statevalue }
})
.success(function (data) {
$('#DDlforLocations').html(data);
});
}
});
And here is my controller
public JsonResult GetLocations(string selectedState)
{
ConsumerNomineeFormEntities db= new ConsumerNomineeFormEntities();
RTOCode tbl = new RTOCode();
var optionList = db.RTOCodes.Where(a => a.State == selectedState).Select(a => "<option value='" + a.Location + "'>" + a.Location + "</option>");
var val = tbl.Location;
return Json(optionList, JsonRequestBehavior.AllowGet);
}
Please help me. To bind the record returning from controller with 2nd dropdown
It is not good idea to mix the code to build your UI markup in your server side code. You may consider returning some data from your server side which you will use in your client side to build the UI markup.
So let's return a list of SelectListItem objects.
var optionList = db.RTOCodes.Where(a => a.State == selectedState)
.Select(c => new SelectListItem { Value = c.Location,
Text = c.Location}).ToList();
And in your ajax call's success event, loop through this array and build the markup for the options.
success : function(data){
var options="";
// options = "<option value='-1'>None</option>"; // uncomment if you want this item
$.each(data,function(a,b){
options+="<option value='"+b.Value+"'>"+b.Text+"</option>";
});
$("#DDlforLocations").html(options);
}
Also, since you are loading the content of the second dropdown via ajax when user selects something on the first dropdown, you may consider changing that to pure clean HTML
<select name="RTOListItem" id="DDlforLocations">
<option value="-1">Select one</option>
</select>

how to fill 2nd combobox with asp.net mvc ajax

I am using aspnet MVC 5 in Visual Studio 2014.1
I have a combobox that is filled with data from the database:
ViewBag.Brans = new SelectList(db.Brans.OrderBy(m => m.Ad), "No", "Ad");
#Html.DropDownList("Brans", null, htmlAttributes: new { #class = "form-control" })
Then i have another combobox. and i want to fill that combobox after i select an option from first combo.
Its like selecting country from the first combo. then cities will appear in the second one.
Does any of you know how to do this?
One of the options is to to make Ajax request to action which will return your list items
public virtual JsonResult GetCountryStates()
{
return Json(
new
{
new List<SelectListItem>() {YOUR ITEMS HERE}
});
}
Then in your Ajax callback body put code like that
function (data) {
//var selValue;
data = $.map(data, function (item, a) {
if (item.Selected) {
selValue = item.Value;
}
return "<option value=\"" + item.Value + "\" " + (item.Selected ? "selected" : "") + ">" + item.Text + "</option>";
});
$('statesSelect').html(data.join(""));
$('statesSelect').val(selValue);
},
#fly_ua : Good way of populating depending dropdown
But what if we post form and on selected value we fetch next dropdown data from our controller and again reload the form? This might be the secure way rather than doing AJAX call.
$('##Html.Encode(Html.IdFor(x => x.YourProperty))')on("Change", function (event) {
event.preventDefault();
var id = $(this).val();
$.ajax({
url: '#Url.Action("ActionName", "ControllerName")',
type: "GET",
data: {
id: id,
},
success: function (result) {
$('##Html.Encode(Html.IdFor(x => x.SecondDropDownProperty))').html(result)
}
});
});
create one view with dropdown and rendor razor JSON with this view
By doing this you will create generic dependent dropdown list.

asp.net mvc2 select value from database according to listbox value

I am using asp.net mvc2.I have a listbox and textbox when i select an item from listbox corresponding value to that item should appear in textbox from database.please help
You should use JavaScript for handle listbox selection changes.
And read about Ajax, it neads to get the data from DB without reloadin page.
Add
Example how can you handle listbox selection changes.
#Html.ListBox("nam",new SelectList(new string[]{"opt1","opt2"}),new {onchange = "javaScript:actch()", id = "namid"})
<script type="text/javascript">
function actch() {
alert(document.getElementById("namid").value);
}
</script>
Value "document.getElementById("namid").value" contains option that you select.
You should send this value to the server and recieve request
#Html.ListBox("nam",new SelectList(new string[]{"opt1","opt2"}),new {onchange = "javaScript:actch()", id = "namid"})
<script type="text/javascript">
function actch() {
$.ajax({
url: "your url",
type: "POST",
data: "id = " + document.getElementById("namid").value,
success: function (data) {
// action on success
document.getElementById("TextBoxId").value = data;
},
error: function (jqXhr, textStatus, errorThrown) {
// action on fail
},
complete: function () {
}
});
}
</script>
You have to write a server request part, and configure ajax.
(I had use jQuery)
Added: Server request part (example)
[HttpPost]
public MvcHtmlString Detail(string id)
{
var d = _db.GetVehicle(Convert.ToInt32(id));
var sb = new StringBuilder();
sb.AppendLine(string.Format("Type: {0}</br>", d.Type));
sb.AppendLine(string.Format("Brand: {0}</br>", d.Brand));
sb.AppendLine(string.Format("Model: {0}</br>", d.Model));
sb.AppendLine(string.Format("Number: {0}</br>", d.Number));
sb.AppendLine(string.Format("Year: {0}</br>", d.Year));
sb.AppendLine(string.Format("Cost: {0}</br>", d.Cost));
return new MvcHtmlString(sb.ToString());
}
URL looks like: MyController/Detail/
DATA for ajax: "id=" + document.getElementById("namid").value
P.S. Some one edit/spoil my ansver and it's not marked(
Your question is a little vague but this is basically how it can be done:
You can post the value of the listbox in the change event by using jquery (or any other JS library of your preference). Then the controller gives a value back, which you then put in the textbox.
Check out http://api.jquery.com/jQuery.post/

Categories