Kendo Drop Down List not showing data - asp.net-mvc

I am trying to create a Kendo Dropdownlist and it will not call the read.Action for some reason. I cannot figure out what I am missing.
I have set the read.Action to different methods and it works but it just will not call it to this specific method. I have verified that I am spelling it correctly and I've set breakpoints on everything to find what it runs.
#(Html.Kendo().DropDownList()
.Name("productionline-dropdown")
.DataTextField("Id")
.DataValueField("Name")
.DataSource(source =>
{
source.Read(read => { read.Action("GetDropDownList", "Home"); });
})
)
[HttpPost]
public JsonResult GetDropDownList()
{
var productionLines = _productionLineService.GetAll().Select(x => new ProductionLineViewModel
{
Id = x.Id,
Name = x.Name,
CreatedAt = x.CreatedAt,
UPE = x.UPE,
ComputerName = x.ComputerName,
ActiveLine = x.ActiveLine
});
return Json(productionLines, JsonRequestBehavior.AllowGet);
}
I want my DropDownList to populate with the Names of the ProductionLines not the Ids. Thanks

This is because the action is decorated with HttpPost, while the control apparently sends Get (quite logically) to fetch the data. Remove this attribute, and that should fix it.

Related

Retrieve all drop-down values from database and show the saved value as selected one in drop down

I am using a kendo grid with pop up editing mode and editor template in mvc4. The template consists of a drop down list which is bound through database. The problem comes when in Edit operation all other data is retrieved along with all elements of drop down list and displayed in respective html attributes such a textbox ,checkbox etc but the value which i have saved from drop down list is not shown auto selected there.
Example
During add operation i have selected "Work" from the drop down list and saved it in database. At the time of Edit i want "Work" to be shown auto selected in drop down list.
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Update([DataSourceRequest] DataSourceRequest request,Model object)
{
if (obj == null || !ModelState.IsValid) return null;
var obj = _Repo.FindBy(t => t.ID == object.ID);
obj.Text = object.Text;
obj.Type = object.Type;
obj.MasterTypeID_Fk = new Guid(object.Type);
obj.Notes = object.Notes;
obj.Primary = object.Primary;
obj.LastVerified = DateTime.Now.ToUniversalTime();
obj.LastUpdated = DateTime.Now.ToUniversalTime();
_Repo.Update(obj);
var result = new[] { object }.ToDataSourceResult(request, ModelState);
return Json(result);
}
//this is my code for ddl in editor template
#(Html.Kendo().DropDownList()
.Name("Type")
.DataTextField("Value")
.DataValueField("TypeID")
.DataSource(source =>
{
source.Read(read => { read.Action("GetTypes", "Dashboard"); });
})
)
// this is code in controller to bind ddl
public ActionResult GetTypes()
{
List<TypeModel> Type = _Repo.GetTypes().ToList().ToMap<TypeBO, TypeModel>();
Type.Insert(0, new TypeModel() { Value = "--Select--", TypeID = Guid.Empty });
return Json(Type, JsonRequestBehavior.AllowGet);
}
You can set your value in Html helper using Value("ValueData"):
#(Html.Kendo().DropDownList()
.Name("Type")
.DataTextField("Value")
.DataValueField("TypeID")
.DataSource(source =>
{
source.Read(read => { read.Action("GetTypes", "Dashboard"); });
})
.Value("ValueData")
)
Like in this example: http://demos.telerik.com/aspnet-mvc/dropdownlist/index

An item with the same key has already been added when loading Kendo MVC Grid

I am trying to populate a Kendo mvcGrid and I keep getting the error An item with the same key has already been added.
I have seen elsewhere that duplicate model properties is the likeliest source of the problem but I have no duplicate properties in my model. I've even simplified everything to just a basic mock up to eliminate as many possible variables as possible..and I cant get the grid to load data.
I've tried it as a Html.Partial where its not loaded initially because of a empty model and then loading it through jquery...Ive tried with passing in am empty model so that the grid will load initially without data and then doing a datasource refresh...no luck there either. Basically as soon as I try to add content to the grid with a populated model I get the error and no data is loaded.
Been fighting this issue for 2 days now and had no luck. Ill post my code here maybe someone else can see what I'm missing.
One variable that cant change is the grid resides on a partial view with a model different from its parent view.
in the parent view I have tried both
<div id ="columnkgrid">#{Html.RenderPartial("Columns", new TestFieldIssue.Models.FieldListModel());}</div>
and
<div id="columnkgrid">#Html.Partial("Columns", new TestFieldIssue.Models.FieldListModel())</div>
either way will succeed in posting a grid with no data..it has no data yet because its populated by the selection of a value in a dropdown list.
so as to not over complicate the sample I've just set a hard coded value in the jquery function I have been using to refresh the grid.
function loadgrid() {
var grid = $("#grid").data("kendoGrid");
var val = 1;
grid.dataSource.read({ table_pk: val });
grid.refresh();
}
the grid code in the partial once again kept it simple without any bells and whistles just to test.
#(Html.Kendo().Grid(Model.fields)
.DataSource(data => data
.Ajax()
.Model(model => model.Id(m => m.field_pk))
.Read(r => r.Action("Columns","Home"))
)
.Name("grid")
.Columns(c =>
{
c.Bound(m => m.field_name).Title("Field Name").Width(100);
})
)
and the controller methods loading some mock data
public ActionResult Columns(int? table_pk)
{
FieldListModel model;
if (table_pk == null)
{
model = GetEmptyColumns();
}
else
{
model = GetColumns();
}
return PartialView("Columns", model);
}
public FieldListModel GetColumns()
{
FieldListModel model = new FieldListModel();
model.fields = new List<FieldModel>();
model.fields.Add(new FieldModel { field_name = "field1", field_pk = 1 });
model.fields.Add(new FieldModel { field_name = "field2", field_pk = 2 });
model.fields.Add(new FieldModel { field_name = "field3", field_pk = 3 });
return model;
}
public FieldListModel GetEmptyColumns()
{
FieldListModel model = new FieldListModel();
model.fields = new List<FieldModel>();
model.fields.Add(new FieldModel { field_name = "", field_pk = 0 });
return model;
}
and a very simple Model
public class FieldListModel
{
public List<FieldModel> fields { get; set; }
}
public class FieldModel
{
public int field_pk { get; set; }
public string field_name { get; set; }
}
I made few changes to run your code (correct version of Kendo and JQuery). May be those related to setup at my machine. I was able to reproduce the problem.
Then I changed the action code and was able to see the values populated in Grid:
public ActionResult Columns(int? table_pk, [DataSourceRequest] DataSourceRequest request)
{
FieldListModel model;
if (table_pk == null)
{
model = GetEmptyColumns();
}
else
{
model = GetColumns();
}
return Json(model.fields.ToDataSourceResult(request));
}
The change is accepting an additional parameter in action method of type DataSourceRequest. The Kendo grid wraps request in this object to specify sorting and paging information. The grid itself gets updated with data wrapped under DataSourceRequest object (note in return statement). More information here.

How to return distinct data to DropDownListFor?

I apply .Net MVC structure with C#. In the controller, I want to distinct specific column (IndustryName), and return the result to Html.DropDownListFor in view. But I get a running time error at view:
System.Web.HttpException: DataBinding: 'System.String' not include
'IndustryName' property.
Is there any one meet such problem, and how to solve it?
Thank you very much for your helping.
Controller:
public ActionResult Create()
{
var industrys = this._pmCustomerService.GetAll().Select (x => x.IndustryName).Distinct();
ViewBag.Industrys = new SelectList(industrys, "IndustryName", "IndustryName", null);
return View();
}
View:
#Html.DropDownListFor(model => model.IndustryName, (SelectList)ViewBag.Industrys)
Your query is returning IEnumerable<string> (you select only the IndustryName property in the .Select() clause. string does not contain an property named IndustryName so you get this error. Just change the SelectList to
ViewBag.Industrys = new SelectList(industrys);
This will bind the options value and display text to the value of IndustryName
The following sample implementation may help you fix the problem:
var industries= this._pmCustomerService.GetAll()
.GroupBy(ind => new { ind.IndustryName})
.Select(group => new SelectListItem
{
Text = group.First().Name,
Value = group .First().Name
}
);
ViewBag.Industries= industries;
You can find more about the 'GroupBy & Select' approach instead of using linq's Distinct(), here
View
#Html.DropDownList("ddlIndustries",(#ViewBag.Industries) as IEnumerable<SelectListItem>)
If you like to use DropDownListFor helper instead then modify view code as follows:
#{
var industries = ViewBag.Industriesas IEnumerable<SelectListItem>;
}
#Html.DropDownListFor(m=> industries , industries )
You get this error because you create SelectList with wrong collection. This should work i think.
var industrys = this._pmCustomerService.GetAll().Select(x => new SelectListItem
{
Value = x.IndustryName,
Text = x.IndustryName
}).Distinct();
ViewBag.Industrys = new SelectList(industrys);
return View();
You are only Selecting IndustryName which is obviously of type String, use DistinctBy() from MoreLinq by Jon Skeet, here is the reference SO post:
public ActionResult Create()
{
var industrys = this._pmCustomerService.GetAll().DistinctBy(x => x.IndustryName);
ViewBag.Industrys = new SelectList(industrys, "IndustryName", "IndustryName", null);
return View();
}

Getting Kendo treeview to work

So I'm trying to get a simple Kendo treeview to bind to JSON data but I am having a hard time. Any ideas why this isn't working? I put a break point on my JSON result code, but it never even fires.
My HTML:
#(Html.Kendo().TreeView()
.Name("treeview")
// The property that specifies the text of the node
.DataTextField("Name")
.LoadOnDemand(true)
.DataSource(dataSource => dataSource
.Read(read => read
// The action method which will return JSON
.Action("ReadCats", "Entity")
.Data("Id")
)
)
)
My Controller:
public JsonResult ReadCats(int? id)
{
var categories = _entityLogic.GetActiveCategories();
var jsonResult = categories.Select(cat => new
{
Id = cat.Id,
Name = cat.Name,
HasChildren = categories.Where(c => c.ParentCategory == cat.Id).Any(),
ParentId = cat.ParentCategory
}).ToList();
return Json(jsonResult, JsonRequestBehavior.AllowGet);
}
Now if I browse to myapplication/Admin/Entity/ReadCats, I do get the JSON data back. Like I said though, the breakpoint never hits when I load the view the tree is on.
Any ideas? I'd note that I've tried every variation of .Action("ReadCats", "Entity") I can think of like: .Action("ReadCats", "/Admin/Entity"), .Action("ReadCats", "~/Admin/Entity"), etc.

Kendo Grid has correct JSON but data not showing up

I'm trying to use Teleric's Kendo Grid in ASP.NET MVC 5. I'm following the example here, but the grid is not populating with data. The columns show up, but it says "No items to display".
http://docs.telerik.com/kendo-ui/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
This is my Words/Read function:
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var items = db.Words.Take(1).ToList();
//this code was necessary to get the correct JSON result
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var converted = JsonConvert.SerializeObject(items, null, jsSettings);
return Content(converted);
}
I got the following JSON result from Words/Read:
[{"WordId":1,"Rank":1,"PartOfSpeech":"article","Image":"Upload/29/1/Capture1.PNG","FrequencyNumber":"22038615","Article":null,"ClarificationText":null,"WordName":"the | article","MasterId":0,"SoundFileUrl":"/UploadSound/7fd752a6-97ef-4a99-b324-a160295b8ac4/1/sixty_vocab_click_button.mp3","LangId":1,"CatId":null,"IsActive":false}]
Finally, my view page:
#(Html.Kendo().Grid<NextGen.Models.Word>
()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(15)
.Read(read => read.Action("Read", "Words"))
)
.Columns(columns =>
{
columns.Bound(c => c.WordName);
columns.Bound(c => c.PartOfSpeech);
})
.Pageable()
.Sortable()
)
I've seen some similar questions to this one, but most are using Javascript rather than Html helpers. Am I doing something dumb?
I found an alternative way to get around the circular reference problem I was having. Basically, the answer is here: A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.
For people with the same problem: I took the two properties I needed - WordName and PartOfSpeech, and passed only those attributes to the toDataSource function Kendo provides.
My new read function looks like this:
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var items = db.Words.Select(w => new WordL{
WordName = w.WordName,
PartOfSpeech = w.PartOfSpeech
});
return Json(items.ToDataSourceResult(request));
}
where WordL is a model with just PartOfSpeech and WordName attributes, rather than all the attributes of my class.
It is probably because you are not using 2 methods in your controller. While your page view is first ActionResult you should use second one as in the grid as you did in your example. I hope it is obvious.
public ActionResult ReadPage()
{
return View();
}
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var items = db.Words.Take(1).ToList();
//this code was necessary to get the correct JSON result
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var converted = JsonConvert.SerializeObject(items, null, jsSettings);
return Content(converted);
}

Resources