I have following dropdown created in cshtml page:
#( Html.Kendo().DropDownList().Name("ddlCode").OptionLabel("Select Code...").BindTo(#ViewBag.dropDown)
.DataTextField("Title")
.DataValueField("domainCode")
I am binding this dropdown on checking of oneof the checkbox on my page.
On checking of checkbox i have called javascript function and written ajax script as follows:
var ddl = $('#ddlCode').data("kendoDropDownList");
$.ajax({
url: "/PP/BindDropDown",
data: {
'Id': paramID
},
dataType: "json",
type: 'POST',
cache: false,
success: function (_data) {
ddl.dataSource.data(_data)
},
error: function () {
//
}
});
BindDropdown of PPController contains code as:
public JsonResult BindDropDown(string ID)
{
List<TEAMS_PP.Entity.correlations> list = new correlation().getDropDownvalues(ID);
ViewBag.dropDown = list;
return Json(list);
}
My problem is when dropdown gets bound it shows its items as "Undefined" as below:
How can i bind this dropdown???
I am using MVC4 Kendo UI Controls
Entity.Correlations:
public correlations() { }
public correlations(DB.EH_PP_DmainComp item)
{
//this.code = Convert.ToInt32( Convert.ToString(item.domainCode));
this.correlatedText = item.description;
this.codeTitle = item.title;
//Component 1a: Demonstrating Knowledge of Content and Pedagogy
//ArrayList arrCode = new ArrayList();
string[] arrCode = Convert.ToString(item.title).Split(':');
string[] code = Convert.ToString(arrCode[0]).Split(' ');
this.code = Convert.ToString(code[1]);
}
public DB.EH_PP_DmainComp ToDB()
{
var rec = new DB.EH_PP_DmainComp();
return rec;
}
public DB.EH_PP_DmainComp ToDB(DB.EH_PP_DmainComp rec)
{
return rec;
}
}
What's happening is that here...
#(Html.Kendo().DropDownList().Name("ddlCode").OptionLabel("Select Code...").BindTo(#ViewBag.dropDown)
.DataTextField("Title")
.DataValueField("domainCode")
You are telling the DropDownList to find the Title and the domainCode property in the correlations class. However, the correlations class does NOT have such properties.
To make this work you have to do one of the followings:
Add a Title and domainCode property to the correlations class
Use a different model object that exposes this property so that the dropdown list can bind to it
Related
// Kendo table sortable
var kendoSortable = grid.table.kendoSortable({
filter: ">tbody >tr",
hint: function (element) { // Customize the hint.
var table = $('<table style="width: 600px;" class="k-grid k-widget"></table>'),
hint;
table.append(element.clone()); // Append the dragged element.
table.css("opacity", 0.7);
return table; // Return the hint element.
},
cursor: "move",
placeholder: function (element) {
return $('<tr colspan="4" class="placeholder"></tr>');
},
change: function (e) {
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
}
});
Im trying to save the order after dragging and reordering. to the database so that when i reload the page the order where i have ordered it would be the exact order when i am reaordering it
Look into using the change event for the Sortable widget. This event provides the oldIndex and newIndex positions for the item that was moved.
Below is an example of one way to go about getting the reordered items and then sending that data to the server to save the changes. Hopefully, this will help you get started with solving your problem.
The change event firing indicates the item has been sorted and the item's position has changed in the DOM. Looking at the change event below, I'm getting the data items for the current page of the grid into currentGridView. Then I'm using the slice() method to get the items between the oldIndex and newIndex. Then I call the updateSequence function.
The updateSequence function creates an array to store objects to be passed to the server. These objects are based on the DataSequenceModel class. Basically, I just need to know the Id and the new sequence for each item that has been reordered. After this I'm using a basic Ajax POST to send the data to the server.
Index.cshtml - Here is a dojo based on Telerik's Integration - Grid demo and updated with my changes.
<div id="grid"></div>
<script>
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
// ...Basic grid setup
}).data("kendoGrid");
grid.table.kendoSortable({
filter: ">tbody >tr",
hint: $.noop,
cursor: "move",
placeholder: function(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
},
container: "#grid tbody",
change: function (e) {
// Get the indexes and data items that have been reordered.
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip;
var currentGridView = grid.dataSource.view();
var dataChanged = currentGridView.slice(oldIndex, newIndex + 1);
updateSequence(oldIndex, dataChanged);
}
});
});
function updateSequence(startIndex, dataChanged) {
// Create array to be passed to Controller. Based on DataSequenceModel class.
let data = [];
let newSequence = startIndex;
for (var i = 0; i < dataChanged.length; i++) {
data.push({ Id: dataChanged[i].ProductID, NewSequence: newSequence });
newSequence++
}
$.ajax({
type: "POST",
url: 'https://localhost:44395/Test/UpdateSequence',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (data) {
console.log(data);
},
error: function (e) {
console.error(e);
}
});
};
</script>
TestController.cs
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
public bool UpdateSequence(IEnumerable<DataSequenceModel> data)
{
// ...Logic to update sequence in database.
return true;
}
}
DataSequenceModel.cs
public class DataSequenceModel
{
public int Id { get; set; }
public int NewSequence { get; set; }
}
We were able to do this with Angular, but are trying to do this with MVC using C# and Razor and possibly jQuery if need be.
What we are trying to do is, we populate a dropdown list with data already populated. (done). In our View we put an onChange event in which we then want to trigger another method in the controller so that we may get another list of items to populate the next droplist.
IN doing some VERY simple examples,we keep either getting a 404 or 500 return in our browser console and not hitting any breakpoints in Visual Studio.
This is what I have so far:
View
<div> #Html.DropDownListFor(model => model.Name, Model.AvailableGalaxyEventTypes, new { #id = "eventTypeName", onchange = "GetEventNames();" })
</div>
<script>
function GetEventNames() {
var url = '#Url.Action("GetData")';
var strId = 0;
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: strId },
success: function (result) {
alert(result);
console.log(result);
$('#result').html(result);
}
});
}
</script>
Controller
public ActionResult GetData(string id)
{
return Json(new { foo = "bar", ball = "dragon" });
}
I don't understand why we are not getting a success or anything back doing this very simple example. I should get Foo and Ball back. If we could get to the controller method, we should be able to make headway but I am getting 404 or 500 now.
Any ideas?
your method is accepting parameter id but you are passing value as parameter in ajax request
data: { id: strId }
or try by specifying controller name as well as action method name explicitly
url: '#Url.Action("Foo", "SomeController")',
#Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)
#Html.DropDownListFor(model => model.RegionId, Model.AvailableRegions)
$("##Html.FieldIdFor(model => model.CountryId)").change(function () {
var selectedItem = $(this).val();
var ddlRegions = $("##Html.FieldIdFor(model => model.RegionId)");
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetRegionsByCountryId"))",
data: { "countryId": selectedItem, "addSelectStateItem": "true" },
success: function (data) {
ddlRegions.html('');
$.each(data, function (id, option) {
ddlRegions.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve regions.');
}
});
And extension method that gets Id of DDL (or you can do it using JQuery or Vanilla JS):
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
And method in controller:
public ActionResult GetRegionsByCountryId(string countryId)
{
var country = _countryService.GetCountryById(Convert.ToInt32(countryId));
var states = _stateProvinceService.GetStateProvinces(country != null ? country.Id : 0).ToList();
var result = (from s in states
select new {id = s.Id, name = s.Title})
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Currently on the I have some inline javascript, which makes an ajax call to a partial view controller which should have updated the viewbag along with it. However this does not seem to be the case, the data seems to persist from the main view which is null because it was never set there and if it was set then the data would still persist(tested).
Here is my javascript ajax call.
$.ajax({
url: btn.data('action-url'),
data: {
id: btn.data('id')
},
type: 'GET',
success: function (data) {
//delete all panels before showing new ones
$('.panel.panel-default').remove();
//push the new panels into the view
//$('#dash-content').html(data);
//Construct the partial view to be input into the main view
//Checks to see if browser supports templates
if ('content' in document.createElement('template')) {
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
for (var i = 0; i < widgetModel.length; i++) {
var clone = loadwidgets(widgetModel[i]); //This function is in an external js file
var inputDestination = document.querySelector('#col2');
inputDestination.appendChild(clone);
console.log(inputDestination);
}
}
and here is the Action that it is calling.
public ActionResult Dashboard(int? id)
{
ModelState.Clear();
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
ViewBag.widgets = getWidgetsQuery.ToList();
return PartialView();
}
Add an action to return the data i.e.
public ActionResult DashboardJson(int? id)
{
//get all widgets associated dashboard
var getWidgetsQuery = (from widgets in db.widgets
where widgets.DashID == id
select widgets);
var widgets = getWidgetsQuery;
return Json(widgets, JsonRequestBehavior.AllowGet);
}
Declare and serialize your model above the json call as you have done:
var widgetModel = #Html.Raw(Json.Encode(ViewBag.widgets));
Then within your success call simply re-assign it to the returned data:
widgetModel = data;
I have a textbox whose value when passed to sp should return a list. I have to bind this list to Dropdown using jQuery Ajax. I have written the sp but my problem is how to bind the dropdown depending on value of textbox in the onblur event of Textbox.
Kindly help. And please excuse for typing errors if any.
i have done similar in my project.
$( "#target" ).blur(function() {
alert( "Handler for .blur() called." );
$.ajax({
url: '../GetRolesAndPriviledgeServlet?filepath='+path+'&type='+type,
type: 'post',
success:function(response){
obj = JSON.parse(response);
$('#DropDownListAssigned').empty();
for (var i=0; i <obj.length ; i++)
{
var oSelField = document.getElementById("DropDownListAssigned");
var oOption = document.createElement("OPTION");
oOption.text = obj[i+1];
oOption.value = obj[i+1];
oSelField.options.add(oOption);
}
},
error:function(){
}
});
});
Try this one
$(document).ready(function () {
$('#txtboxid').focusout(function () {
var yourvalue = $('#textboxid').val();
$.post("/your/url", { Parametername : yourvalue }, function (result) {
$.each(result, function (key, value) {
$('#dropdownid').append($("<option></option>").html(value).val(value));
// Dropdown Binding
});
}, "json");
});
});
Note : Parameter must be same as your controller for example public void data(string nval) means your parameter name also nval
$(document).ready(function ()
{
$(".viewmap").click(function ()
{
var id = $(this).attr("id");
var responseURL = "~/changemap?id=" + id;
//alert(responseURL);
$.ajax(
{
url: responseURL,
dataType: "json",
type:"GET",
success: function (dt)
{
initialize(dt.Latt, dt.Longt);
}
}
);
}
);
});
I use that script to make an ajax call to the page changemap.cshtml which does the following
#{
if(!IsPost)
{
if(!Request.QueryString["id"].IsEmpty()&&Request.QueryString["id"].IsInt())
{
var countryId=Request.QueryString["id"];
var db=Database.Open("GoogleMapView");
var dbCmd="SELECT * FROM places WHERE id=#0";
var row=db.QuerySingle(dbCmd,countryId);
if(null!=row)
{
Json.Write(row,Response.Output);
}
}
}
}
That is to return the queried data from the database in json format to the client. The Initialize function is defined as
function initialize(lat,lng)
{
var mapOptions = {
center: new google.maps.LatLng(lat,lng),zoom: 8,mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("gmap"),mapOptions);
}
But when I click the div tag of class viewmap, nothing happens. I think I miss some more script to get my application to work correctly.
I only try to implement a simple google map view in which once the user clicks a place name as a hyperlink will reload the map that matches with it.
I think
var responseURL = "~/changemap?id=" + id;
should be
var responseURL = '#(Url.Content("~/changemap")+"?id=")' + id;
try thr following
success(data){
initialize(data.d.Latt, data.d.Longt);
}
for more reference as in why d is used check the following link
http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/