Data Filter - View User Interface - javascript

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' />

Related

Accessing Other Entities Attributes in Dynamics CRM/365 Forms with javaScript

This function buttonBuzz() works inside the Forms of the Entities Account, Contacts and Leads. But not in the Opportunity form.
Mainly because there is no telephone1 attribute. There is however a Contact entity added with "Quick View" in a section with a telephonenumber inside.
I think it can be accessed with the telephone1 as well just not with Xrm.page
Any ideas how i can grab the attribute from inside the "quick view"?
I dont know if the "Quick view" window is a form of an iFrame. And if it is i have no clue how to access it with the Xrm.Page.getAttribute("telephone1").getValue();
function buttonBuzz(exObj) {
var phoneNumber;
// Here i store the "telephone1" Attribute from the current .page
phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();
if (phoneNumber != null) { **Sends phonenumber** } ...
Quick Views display data from a record selected in a lookup field, in this case a Contact. You can query data from related records using the OData endpoint.
You first need to get the Guid of the record selected:
var contactId = Xrm.Page.getAttribute("parentcontactid")[0].id || null;
You would then need to send a SDK.REST request, passing parameters for the Id of the record (contactId), entityName and the columns:
var entityName = "Contact";
var columns = "Address1_Telephone1, FirstName, LastName";
SDK.REST.retrieveRecord(contactId, entityName, columns, null, function(result) {
// Success, logic goes here.
var address1_Telephone1 = result.Address1_Telephone1;
}, function(e) {
console.error(e.message);
});
As well as your JavaScript file, you would need to include the SDK.REST.js file that is included in the MS CRM SDK download within your Opportunity form libraries.
You can pull that field up from the Contact into the Opportunity by creating a Calculated Field, setting it equal to parentcontactid.telephone1
Put the field on the form, and you'll be able to .getAttribute() it like any other Opportunity field (being Calculated, it updates itself whenever the source changes).

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!

ViewModel current state to JSON

I have an issue with aps.net mvc project. I have a view where is set list of check boxes inside of begin form, then on submit appropriate fields are shown as a report. So I have to add a button to my view, where user is setting which fields he d like to see, so as he could save all checkbox values as a preset with its name.
I have model with a lot of nested models it looks like this:
public class EmployeeOverallReport
{
public List<PersonalData> ListOfPersonalData { get; set; }
public EmployeeOverallReportBool ColumnsNeeded { get; set; }
public EmployeeOverallReportFilters ModelFilters { get; set; }
}
I actually need ColumnsNeeded model, which has alot of bool properties for storing each checkbox value (true/false).
So on click I have to get current state of checkboxes and make a post with these model values.
I have been trying to serialize my form:
var data = $('#myForm').serialize();
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
I got JSON string but it was invalid and i could not deserialize it back.
Here is what I am trying to do now:
$("#savePresetButton").on('click', function () {
var url = "/Reports/SavePreset";
var data = #Html.Raw(Json.Encode(Model));
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
});
this code is using my viewModel with its properties, where all ColumnsNeeded properies are set to false, as it is by default and all user side changes in a view are not set to model yet, so as my form was not submitted and values were not changed.
How could I get current state of all checkboxes on user side?
Not doing it like :
var dataset = {
CategoryBool: $("#ColumnsNeeded_CategoryBool").val(),
NameBool: $("#ColumnsNeeded_NameBool").val(),
KnowledgeLevelBool: $("#ColumnsNeeded_KnowledgeLevelBool").val(),
SkillAdditionalInfoBool: $("#ColumnsNeeded_SkillAdditionalInfoBool").val(),
...
}
because I have more than 90 properties there..
I am sorry for this post, but posting some code is impossible due to count of properties inside the model.
Could you serialize the entire form and ajax submit the form itself?
see: Pass entire form as data in jQuery Ajax function

x-editable submit additional "array" to the total AJax POST data

I'm trying to add an array of object to the post data of a group of bootstrap x-editable in my jsp page.
I recover the data from a table, and build an array of object. After do that, I need to append this array to the list of the other value posted by the editables in the page.
I've an html table with id="user" and this code recover data from it and build the array of object. This is my code, that works and produces the correct object:
function recover_data() {
console.log("Starting recover");
var beneficiary_list = [];
$('.lav').each(function() {
var obj = {'company': $(this).attr('id'), 'num':$(this).text() };
beneficiary_list.push(obj)
});
console.log(beneficiary_list); //output to check array produced
return beneficiary_list;
};
this function is what I call from a save button, that launch my global submit retrieving data from all editable in the page and adding in the "params" the array returned from recover_data(), in this way:
jQuery('#data a').editable('submit',{
url:'test/prove/data_received',
params: function(params) {
params.beneficiary = recover_data();
return params;
},
success:function(resp){ ... }
})
but testing with Postman (Chrome) the produced output to POST, is without the array. Are submitted only the "editables" data, but no "beneficiary" field with array of that values adding. The missing field must be like
"beneficiary": [0: company: "1", num: "22" ..etc..]
How can I "append" to the produced POST data from a group of editables an array of objects, like that I've show?
Looking to this page is possible
Question on github x-editable page
I don't understand why don't works...I follow the example written on second post from vitalets, he wrote:
editable({
...
params: function(params) {
params.checked = ... //get array of checked values
return params;
}
});
To Explain better what I need: I've a Java Controller (servlet) that receive a modelView object (POJO) with several fields (that came from other editables in the page) and a field "ArrayList beneficiary" where Beneficiary is a small object of two fields "company" and "num"
public Class Beneficiary{
private String company;
private String num;
//then get e set methods..
}
instead, my POJO is like:
import java.util.ArrayList;
import Beneficiary;
public class Module {
private Integer id;
private String titolo;
private String companyRating;
private ArrayList<Beneficiary> beneficiary;
//get e set methods
In the console I obtain the correct object for that voice
but not in the post object that is like
instead I need that the produced output "beneficiaries" field to POST url is something similar to this example (found on internet)
How can I obtain a list of that object from my JSP page when submit?
Someone can help me?
params is an option for editable object, while you are using it as options for ajax call.
Your code should look like:
$('#data a').editable({
url: "/post"
});
and then the submit() (note selector for all of your editable objects):
$('.editable').editable('submit', {
data: {beneficiary: recover_data()},
success:function(resp){ ... }
});
Working fiddle. Check your console to see logs

Kendo UI Grid - Display foreign key value instead of ID

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.

Categories

Resources