Kendo Grid Custom comboBox Filter - asp.net-mvc-4

I has grid which will load data as filterable combo box, So I need to create custom filter for this column with filterable combo box also.
I create combo box and assign it to the column filter UI. My problem is when the combobox read the data from the controller it does not send the filter text to the controller.
<script type="text/javascript">
function outletFilter(element) {
debugger;
element.kendoComboBox({
dataTextField: "OutletNameE",
dataValueField: "OutletID",
autoBind: false,
minLength: 1,
dataSource: {
serverFiltering: true,
transport: {
read: "#Url.Action("GetOutletsCombo")"
}
},
optionLabel: "--Select Value--"
});
}
</script>
#(Html.Kendo().Grid<Spine.ERP.ViewModel.AccountReceivableOutletViewModel>()
.Name("ARDetails_OutletGrid")
.Columns(columns =>
{
columns.Bound(p => p.AccountReceivableID).Hidden();
columns.Bound(p => p.AccountReceivableOutletID);
columns.Bound("Outlet.OutletName")
.EditorTemplateName("OutletForeignKeyEditor")
.ClientTemplate("<a>#=OutletID ##=OutletID? '-' : ' ' ##=OutletID ?
Outlet.OutletName : ' ' #</a>")
.Filterable(filter => filter.UI("outletFilter"));
})
And here are my controller function
public ActionResult GetOutletsCombo(string text)
{
if (text == null)
text = "";
var result = new List<OutletViewModel>();
var Outlets = outletRepository.FilterOnID("Outlet", new string[] { "OutletID", "OutletNameE" }, text).ToList();
result = (from outlet in Outlets
select new OutletViewModel
{
OutletID = outlet.OutletID,
OutletNameE = outlet.OutletNameE,
OutletNameA = outlet.OutletNameA
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}

First of all if you perform a "read", it does not send any additional value to the controller so in "public ActionResult GetOutletsCombo(string text)" you wouldn't get any value in "text".
For server filtering you can see kendo's demo on the following page
http://demos.kendoui.com/web/combobox/serverfiltering.html
As far as I get from your question, you want to do a Kendo Grid and on there you want to have a combobox to filter the data in the grid. In this case, you may check the similar kind of demo in Kendo's site
http://demos.kendoui.com/web/grid/toolbar-template.html
For filter menu you can check this on kendo under ASP.NET MVC
http://demos.kendoui.com/web/grid/filter-menu-customization.html
Hope you can work out your problem from these examples. In case you can't then put a comment underneath this post. I shall try again to help you.

Related

asp.net MVC autocomplete with Html.TextBoxFor

I am modifying a preexisting application. I am trying to add the jquery autocomplete functionality. I have it working and calling the controller but the problem is the name attribute in the input field is "someClass.someMethod" so because I can't put this in the controller parameter like this, but still want to satisfy asp.net's Model Binding rules, what can I do?
Controller:
public JsonResult GetPs(string pN, PSModel pS)
{
List<string> pNs = null;
pNs= pS.PEntryBL.BusinessLayerPS.PS
.Where(x => x.Text.StartsWith(pN)).Select(y => y.Text).ToList();
return Json(pNs, JsonRequestBehavior.AllowGet);
}
View:
$(function () {
$("#autoCompletePNBox").autocomplete({
source: '#Url.Action("GetPs", "PS", new {pS = #Model})'
});
});
In Form:
#Html.Label("Scan PN: ", new { #class = "DFont"})
#Html.TextBoxFor(r => r.PEntryBL.PS, new { #class = "pageFont", id = "autoCompletePNBox" })
Using This Post
I was able to get it working by grabbing the value of the input field and passing it on each function call (or each time a user enters a character).
Now when the user selects the item from the autocomplete list, and selects submit then the frameworks form model binding behind the scenes will still work as originally implemented.
Here is the jquery code change:
<script type="text/javascript">
$(function () {
var src = '#Url.Action("GetPs", "PS", new {pS = #Model})'
$("#autoCompletePNBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
pN: $("#autoCompletePNBox").val()
},
success: function (data) {
response(data);
}
});
}
});
});
I couldn't figure this out right away as my Jquery skills are not very strong. Hopefully this helps someone.

mvc4 partial view used twice on the same view

I have a partial view for cascading drop downs i.e. Country and State. I am using the following razor view statement to render this partial view
#{Html.RenderAction("PopulateCountriesDropdown", "Helper");}
and it works just fine. Following is the complete code for the partial view that makes an asynchronous call to an action method of the controller
<pre>#model OnlineExamSystem.Models.CountryAndStateViewModel
#Html.LabelFor(m => m.c.CountryName)
#Html.DropDownListFor(m => m.c.CountryId, new SelectList(Model.cntlist, "CountryId", "CountryName"),"--Select Country--", new { #class="aha" })
#Html.Label("State")
Note: since i am unable to write HTML i.e. I have a simple html select for displaying 2nd drop down to show states with class="ddlstates"
<script type="text/javascript">
$(document).ready(function () {
$(".aha").change(function () {
var Url = '/Helper/PopulateStateDropdown';
var catId = $(this).val();
//alert(catId);
var select = $('.ddlstate');
if (catId != '') {
$.getJSON("/Helper/PopulateStateDropdown", { id: catId },
function (ddl) {
select.empty();
select.append($("<option></option>", { value: 0, text: '--Select State--' }));
$.each(ddl, function (index, itemData) {
select.append($("<option></option>", { value: itemData.Value, text: itemData.Text }));
});
});
}
else {
select.empty();
select.append($("<option></option>", { value: 0, text: '--Select State--' }));
}
});
});
as i said this works just fine. but here is the problem i.e. when I try to render the same partial view again on the same page (view) as following
#{Html.RenderAction("PopulateCountriesDropdown", "Helper");}
the rendering is ok, but changing the country in the 2nd partial view does not select the states properly. Also I have noticed that following action method is called twice for the first partial view
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult PopulateStateDropdown(string id)
{
var ls = State.GetStateByCountryId(Int32.Parse(id)).AsEnumerable();
var ddl = ls.Select(m => new SelectListItem() { Text = m.StateName, Value = m.StateId.ToString() });
return Json(ddl, JsonRequestBehavior.AllowGet);
}
and interestingly the the above method is not at all called from the 2nd partial view.
(doucment).ready() binds event to the dome elements when the page is loaded first time, it finds the elements in DOM and bind events to them, in your case as its a partial view, html is rendered dynamically on page after page is loaded so event is not binded.
Use live function for event as you html is dynamically added on the view:
Do like this:
$(".aha").live('change',function () {
});

Can we implement On key up filter option in Yii's cGridview?

I am currently trying to implement automatic filtering in Yii cGridview, By default it filters 'onclick', or 'enter' key press, But I need to change that event to "onkeyup"|
my code is like this
Yii::app()->clientScript->registerScript('search',"
$('.filters > td >input').keyup(function(){
$('#grid-id').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
when I entered the first letter filtering occured, but after filtering and rendering the code fails.. please give me a solution.. Is there any php yii gridview extension which has filtering onkeyup
You need to change the way you attach the keyup listeners. After the gridview refreshed through AJAX, all elements inside the grid are replaced. So there's no keyup attached anymore. You can try something like:
$('body').on('keyup','.filters > td > input', function() {
$('#grid-id').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
#Michael Härtl's answer is right. But 2 Problem occur when you use this code.
1) When User Search in filter at that time, every time grid will be refresh so focus of input box will be lost.
2) When you search in one filter input and if you go to second input field field at that time first input box will be lost.
So now I have got the solution for that.
Set this java script code on your grid view.
Yii::app()->clientScript->registerScript('search', "
$('body').on('keyup','.filters > td > input', function() {
$(document).data('GridId-lastFocused',this.name);
data = $('#GridId input').serialize();
$('#GridId').yiiGridView('update', {
data: data
});
return false;
});
// Configure all GridViews in the page
$(function(){
setupGridView();
});
// Setup the filter(s) controls
function setupGridView(grid)
{
if(grid==null)
grid = '.grid-view tr.filters';
// Default handler for filter change event
$('input,select', grid).change(function() {
var grid = $(this).closest('.grid-view');
$(document).data(grid.attr('id')+'-lastFocused', this.name);
});
}
// Default handler for beforeAjaxUpdate event
function afterAjaxUpdate(id, options)
{
var grid = $('#'+id);
var lf = $(document).data(grid.attr('id')+'-lastFocused');
// If the function was not activated
if(lf == null) return;
// Get the control
fe = $('[name=\"'+lf+'\"]', grid);
// If the control exists..
if(fe!=null)
{
if(fe.get(0).tagName == 'INPUT' && fe.attr('type') == 'text')
// Focus and place the cursor at the end
fe.cursorEnd();
else
// Just focus
fe.focus();
}
// Setup the new filter controls
setupGridView(grid);
}
// Place the cursor at the end of the text field
jQuery.fn.cursorEnd = function()
{
return this.each(function(){
if(this.setSelectionRange)
{
this.focus();
this.setSelectionRange(this.value.length,this.value.length);
}
else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', this.value.length);
range.moveStart('character', this.value.length);
range.select();
}
return false;
});
}");
Add this line to your gridview widget code.
'afterAjaxUpdate'=>'afterAjaxUpdate',
For example:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'GridId',
'afterAjaxUpdate'=>'afterAjaxUpdate',
));

how to call a controller method in asp.net mvc and show the details in labels in the view

I have a view with a text box, when I type and enter a service number then it should retrieve the data from the database and show those in labels in the same view, This application is ASP.net MVC application. Can some one tell me how to do this. Thanks
Further more
can I call controller methods without javascript
Is that possible to call controller methods in view and show the results in the same view
If can the show me how to do it, Thanks
You could use AJAX. Let's have an example:
#Html.LabelFor(x => x.FooBar, htmlAttributes: new { id = "fooBarLabel" })
#Html.TextBoxFor(x => x.FooBar, new { id = "fooBar", data_url = Url.Action("CalculateValue") })
and then in a separate javascript file you could subscribe to the .change event of the text field and trigger an AJAX call to the controller action:
$(function() {
$('#fooBar').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$('#fooBarLabel').load(url, { value: value });
});
});
and all that's left is the corresponding controller action:
public ActionResult CalculateValue(string value)
{
// The value parameter will contain the text entered by the user in the text field
// here you could calculate the value to be shown in the label based on it:
return Content(string.Format("You entered: {0}", value));
}

how to do postback on changing dropdownlist selected item in mvc4

I have a dropdown in my page. On selecting a value in dropdown I want the label text to be changed. Here is my code :
#model FND.Models.ViewLender
#{
ViewBag.Title = "Change Lender";
}
#using (Html.BeginForm())
{
#Html.Label("Change Lender : ")
#Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes)
#Html.DisplayFor(model => model.Description)
}
On changing the value in dropdownlist I want the Description to change accordingly.
You could start by putting the description into a div and give your dropdown an unique id:
#model FND.Models.ViewLender
#{
ViewBag.Title = "Change Lender";
}
#using (Html.BeginForm())
{
#Html.Label("Change Lender : ")
#Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes, new { id = "lenderType" })
<div id="description">
#Html.DisplayFor(model => model.Description)
</div>
}
Now all that's left is to subscribe to the onchange javascript event of this dropdown and update the corresponding description.
For example if you are using jQuery that's pretty trivial task:
$(function() {
$('#lenderType').change(function() {
var selectedDescription = $(this).find('option:selected').text();
$('#description').html(selectedDescription);
});
});
This being said I probably misunderstood your question and this description must come from the server. In this case you could use AJAX to query a controller action that will return the corresponding description. All we need to do is provide the url to this action as an HTML5 data-* attribute to the dropdown to avoid hardcoding it in our javascript file:
#Html.DropDownList(
"Ddl_Lender",
Model.ShowLenderTypes,
new {
id = "lenderType",
data_url = Url.Action("GetDescription", "SomeController")
}
)
and now in the .change event we trigger the AJAX request:
$(function() {
$('#lenderType').change(function() {
var selectedValue = $(this).val();
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
data: { value: selectedValue },
success: function(result) {
$('#description').html(result.description);
}
});
});
});
and the last step of course is to have this controller action that will fetch the corresponding description based on the selected value:
public ActionResult GetDescription(string value)
{
// The value variable that will be passed here will represent
// the selected value of the dropdown list. So we must go ahead
// and retrieve the corresponding description here from wherever
// this information is stored (a database or something)
string description = GoGetTheDescription(value);
return Json(new { description = description }, JsonRequestBehavior.AllowGet);
}