Kendo UI Grid - Display foreign key value instead of ID - javascript

The grid uses a drop down list that contains foreign key values. Right now, I can select an item but I can only see the corresponding item ID instead of it's name in the grid.
I tried following the steps in this post but all I see is 'undefined' in the grid row. Any ideas?
By the way, I'm using the open source version of Kendo UI where everything is in JavaScript.

This is the MVC version, but here, you don't need a template. See:
http://decisivedata.net/kendo-ui-grid-and-entity-framework-code-first-foreign-key-fields/
Say you want to get the Product name, instead of use ProductID on your Orders table. You'd use a column like:
columns.ForeignKey(c => c.ProductID, (IEnumerable)ViewData["Products"], dataFieldText: "ProductName", dataFieldValue: "ProductID");
And ensure your model had the foreign key in the Orders model:
[ForeignKey("ProductID")]
public Product FKProduct { get; set; }
And you update the controller:
public class HomeController : Controller {
private NorthwindRepository northwindRepository = new NorthwindRepository();
public ActionResult Index()
{
PopulateProducts();
return View(northwindRepository.OrderDetails);
}
private void PopulateProducts()
{
ViewData["Products"] = northwindRepository.Products;
}
}

I eventually requested for support from Telerik and the working solution is shown in this JS Bin.

You need to use a template.
In your model have another field which relates to the name (you will need to set this to the correct value when editing), then use a template like
"#=name#
Firstly create your column like this:
columns.Bound(x => x.ForeignKey).ClientTemplate("#=Name#");
then in your Update method in your controller set the Name property on the view model to what you want it to be.
viewModel.Name = GetName(viewModel.ForeignKey);
return this.Json(new[] { viewModel }.ToDataSourceResult(request, this.ModelState));
Edit 2:
For building the grid in javascript mode you will need to define the column like this:
{ field: "ForeignKey", title: "Foreign Key", template: '#=Name#', editor: myEditor}
Then define your editor like this:
function myEditor(container, options) {
$('<input required data-text-field="ForeignKeyName" data-value-field="ForeignKey" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: myDataSource
});
}
You may still need to set the value however, if you want to do it on the server side you can use use the method I mentioned above, if you want to do this client side you will need to handle the grid save event and set the value in the data source there.
hope this helps.

Related

Updating a Partial View in MVC 5

I am getting an error when trying to load a partial view that should display a list on the create view of the MVC app. The list is based on a value will come from a list of values drop control.
On create view there is no selection so the list is empty and will need to refreshed after the user selects a value while in the MVC create view.
I followed the accepted answer on this question and got errors:
Updating PartialView mvc 4
But I have some questions about what is being said.
Someone said: "There are some ways to do it. For example you may use jQuery:" and he shows the Java query.
But he also shows another method and says: "If you use logic in your action UpdatePoints() to update points"
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
I get the following error
The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult UpdateList(Int32)' in 'System.Controllers.RController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
I have no clue what this error means
So in create view:
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PVList">
#{ Html.RenderAction("UpdateList");}
</div>
</div>
In controller under the create action as its own function
[HttpGet]
public ActionResult UpdateList(int ID)
{
if (ID != 0)
{
ViewBag.List = Get_List(ID);
return PartialView("PV_List");
}
else
{
ViewBag.List = "";
return PartialView("");
}
}
And the function that makes the list for the view bag function:
private List<SQL_VIEW_LIST> Get_List(int ID)
{
return db.SQL_VIEW_LIST.Where(i => i.ID == ID).ToList();
}
The JavaScript for the for the list of values drop down list of values: That also controls turning on the visibility of the list when it has data:
//Fire The List to make visible after list values select
$(document).ready(function () {
$('#RES_VEH_ID').change(function ()
{
$("#PV_List").show(); // Shows Edit Message
$.post('#Url.Action("PostActionTo_Partial","Create")').always(function()
{ ('.target').load('/Create'); })
});
})
Also does anyone know what this string mean: ? "PostActionTo_Partial"
Also does anyone know what this means ViewBag.points = _Repository.Points; I get the view bag part but it's the _Repository.Points; part that I don't understand. Any one have any ideas of what is going on there?
I can't understand what do you try to do. But i'll try to answer.
I have no clue what this error means.
This error means that model binder can't find parameter "ID" for action method
public ActionResult UpdateList(int ID)
Because you don't send any parameter for this method:
You can try this:
#{ Html.RenderAction("UpdateList", new {ID="value"});}
Or you can set default value in your method:
public ActionResult UpdateList(int ID=value)
or make "ID" nullable:
public ActionResult UpdateList(int? ID)
Also does anyone know what this string mean: ? "PostActionTo_Partial"
this is "action name" in yor controller
Also does anyone know what this means ViewBag.points =
_Repository.Points;
it means assigning dynamic object "VivBag.points' data to transfer them into view
So with help from Matt Bodily You can Populate a Partial View in the create view triggered by a changed value in a drop down list using a view
bag and something called Ajax. Here is how I made my code work.
First the partial view code sample you need to check for null data
_WidgetListPartial
#if (#ViewBag.AList != null)
{
<table cellpadding="1" border="1">
<tr>
<th>
Widget Name
</th>
</tr>
#foreach (MvcProgramX.Models.LIST_FULL item in #ViewBag.AList)
{
<tr>
<td>
#item.WidgetName
</td>
</tr>
}
</table>
}
Populating your View Bag in your controller with a function
private List<DB_LIST_FULL> Get_List(int? VID)
{
return db.DB_LIST_FULL.Where(i => i.A_ID == VID).ToList();
}
In your Create controller add a structure like this using the [HttpGet] element
this will send you data and your partial view to the screen placeholder you have on your create screen The VID will be the ID from your Drop
down list this function also sends back the Partial View back to the create form screen
[HttpGet]
public ActionResult UpdatePartialViewList(int? VID)
{
ViewBag.AList = Get_List(VID);
return PartialView("_WidgetListPartial",ViewBag.AList);
}
I am not 100% if this is needed but I added to the the following to the ActionResult Create the form Id and the FormCollection so that I could
read the value from the drop down. Again the Ajax stuff may be taking care if it but just in case and the application seems to be working with
it.
This is in the [HttpPost]
public ActionResult Create(int RES_VID, FormCollection Collection, [Bind(Include = "... other form fields
This is in the [HttpGet] again this too may not be needed. This is reading a value from the form
UpdatePartialViewList(int.Parse(Collection["RES_VID"]));
On Your Create View Screen where you want your partial view to display
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PV_WidgetList">
#{ Html.RenderAction("UpdatePartialViewList");}
</div>
</div>
And finally the Ajax code behind that reads the click from the dropdown list. get the value of the selected item and passed the values back to
all of the controller code behind to build the list and send it to update the partial view and if there is data there it pass the partial view
with the update list to the create form.
$(document).ready(function () {
$('#RES_VID').change(function ()
{
debugger;
$.ajax(
{
url: '#Url.Action("UpdatePartialViewList")',
type: 'GET',
data: { VID: $('#RES_VID').val() },
success: function (partialView)
{
$('#PV_WidgetList').html(partialView);
$('#PV_WidgetList').show();
}
});
This many not be the best way to do it but this a a complete an tested answer as it work and it is every step of the process in hopes that no
one else has to go through the multi-day horror show I had to go through to get something that worked as initially based on the errors I thought
this could not be done in mvc and I would have to continue the app in webforms instead. Thanks again to everyone that helped me formulate this
solution!

ASP.NET dropdown list options depends on chosen option in other dropdown list

I have simple ViewModel that I passed to view in my application, it has two SelectLists with several options like, e.g:
public class MyViewModel {
public SelectList Names { get; set;} // e.g options - N1,N2,N3
public SelectList Years { get; set;} // e.g options - Y1,Y2,Y3
}
There are several options defined for each of those SelecLists. In my view I have two DropDownListFor in which user can easily choose option - it's independent.
But what I want to do is that, when user choose in 1st dropdownlist option N1, then in second dropdown list will be available only options Y2,Y3. When user choose N2, in second one will appear only N3 etc.
Something with jQuery maybe? How to get information which option is currently chosen in particular dropdown list? With JavaScript?
Yes it ist possibile with javascript.
First you need to get the selected option from the dropdownlist by using javascript or Jquery for example like this:
yourSelect.options[ yourSelect.selectedIndex ].value
then you have to set an disabled attribute with either javascript or jquery.
The answer in this post here might be helpful.
Furthermore look at this example
If you want them to be completely deleted then you wolud need to take them out by deleteing the node using JQuery for example.
I solved my issue with jQuery, if someone will need it:
#Html.DropDownListFor(model => model.Name, Model.Names, "Wybierz rodzaj", new { #class = "form-control", onchange="setRateOptionsByDepositType(this.value)"})
.js file:
function setRateOptionsByDepositType(type) {
if (type === "Lokata standardowa") {
$('#rate').prop('selectedIndex', 0);
$('option[value="0,60"]').hide();
$('option[value="1,70"]').show();
$('option[value="2,00"]').show();
$('option[value="2,20"]').show();
$('option[value="2,70"]').show();
}
else if (type === "Rachunek oszczędnościowy") {
$('#rate').prop('selectedIndex', 0);
$('option[value="0,60"]').show();
$('option[value="1,70"]').hide();
$('option[value="2,00"]').hide();
$('option[value="2,20"]').hide();
$('option[value="2,70"]').hide();
}
}
Where rate is id of other dropdownlist in this page

Jquery exporting table to csv hidden table cells

I need to be able to export a HTML table to CSV. I found a snippet somewhere; it works but not entirely how I want it to.
In my table (in the fiddle) I have hidden fields, I just use quick n dirty inline styling and inline onclicks to swap between what you see.
What I want with the export is that it selects the table as currently displayed. so only the td's where style="display:table-cell". I know how to do this in normal JS.
document.querySelectorAll('td[style="display:table-cell"])');
but how can I do this using the code I have right now in the exportTableToCSV function?
(sorry but the text in the fiddle is in dutch as its a direct copy of the live version).
The fiddle:
http://jsfiddle.net/5hfcjkdh/
In your grabRow method you can filter out the hidden table cells using jQuery's :visible selector. Below is an example
function grabRow(i, row) {
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
//Added :visisble to ignore hidden ones
var $cols = $row.find('td:visible');
if (!$cols.length) $cols = $row.find('th:visible');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
Here's how i solved it. Decided to step away from a pure javascript solution to take processing stress off the client and instead handle it server side.
Because i already get the data from the database using a stored procedure i use this to just get the dataset again and convert it into an ViewExportModel so i have a TotalViewExport and a few trimmed variations (reuse most of them) based on a Selected variable i fill a different model.
Added to the excisting show function to update a Selected variable to keep track of the currently selected view.
When the user clicks Export table to excel it calls to the controller of the current page, IE. AlarmReport (so AlarmReportController) and i created the action ExportReports(int? SelectedView);
In addition i added CsvExport as a manager. This takes data results (so c# models/ iqueryables/ lists/ etc). and puts them into a Csv set. using the return type BinaryContent one can export a .csv file with this data.
The action ExportReports calls the stored procedure with the selectedview parameter. The result gets pumped into the correct model. this model is pumped into the CsvExport model as rows.
The filename is made based on the selected view + What object is selected + current date(yyyy-MM-dd). so for example "Total_Dolfinarium_2016-05-13". lets
lastly the action returns the .csv file as download using the BinaryContent Returntype and ExportToBytes from the CsvExport
The export part of this action is programmed like so(shortened to leave some checks out like multiple objects selected etc)(data and objectnames are gathred beforehand):
public ActionResult ExportCsv(CsvExport Data, string ObjectName, string Type){
var FileName = Type + "_" + ObjectName + "_" + DateTime.Now.ToString("yyyy/MM/dd");
return BinaryContent("text/csv", FileName + ".csv", Data.ExportToBytes());
}

Using read function of oData model in UI5

I am coding an UI5 App which consumes a given OData Service. Now I want to get the name of an account with a given account number and Display it in a table. As I can only access the account Name via /AccountInfoSet()/ShortText I tried to use a formatter function to map the account number.
Binding in View:
Formatter function in Controller:
numToNameFormatter : function(sNum){
var text = this.getView().getModel().read("/AccountInfoSet('" + sNum + "')", null, null, true,
function(oData, oResponse){
return JSON.stringify(oData);
},
function(){
alert("Read failed");
});
return text;
}
This should return the requested object as a string. The data is requested successfully, as I verified via an alert. The problem is, that I can't get the data out of the call back, as it ist asynchronous. How do I get the data.
Thanks in advance!
Not sure if your data model is set up like this, but would it be possible to expand your table set to also load the related AccountInfoSet's?
I mean, if your table holds for instance an array of Accounts, and each Account entry has a related AccountInfo, you could just fill your table with the following:
http://your.service/Accounts/?$expand=AccountInfo
You then bind the field in your table directly, without a formatter:
<TextField value="{AccountInfo/0/ShortText}">

Data Filter - View User Interface

I have an Asp.Net MVC web app that I need to provide a user interface in the view to apply data filters to display a subset of the data.
I like the design of what is used on fogbugz with a popup treeview that allows for the selection of data filters in a very concise manner: http://bugs.movabletype.org/help/topics/basics/Filters.html
My controller's action method has some nullable parameter's for all of the available filters:
public ActionResult EmployeeList(int? empId, int? month, int? year,
string tag1, string tag2 //and others....)
{
//...filter employee list on any existing parameters
return View(viewModel);
}
My intention was whenever a filter was applied by clicking on a link, entering text...that filter would be added to the parameter list and reload the page with the correct data to display.
Looking for some guidance or examples on how to create a filter toolbar or best practices for this type of problem. I haven't been able to find a jquery ui plugin or javascript library to do something similar to this so a little lost on where to start.
Thanks.
I did something similar to this by having a main page containing a number of dropdowns containing the parameter options, then a div that had the resultant set ViewUserControl loaded into it on both page load and on dropdown selection change. The controller for the data, in this case TaskList, just needs to return a normal ActionResult View(newTaskList(data)); Example below.
<script>
$(document).ready(function () {
loadDataSet();
});
function loadDataSet(){
var status = document.getElementById('ddlStatus');
var selectedStatus = status.options[status.selectedIndex].value;
if (status.selectedIndex == 0) selectedStatus = '';
$.post('<%= Url.Action("TaskList") %>', { status: selectedStatus },
function (data) {
$('#divTaskList').html(data);
});
}
</script>
<%= Html.DropDownList("ddlStatus", Model.StatusOptions, null, new { onchange = "javascript:loadDataSet();" })%>
<div id='divTaskList' />

Categories

Resources