Answered by:
MVC Grid (not third party)

Question
-
User1096912014 posted
Hi everybody,
I googled on 'jquery sample MVC' hoping to find a way to implement progress bar and numeric textbox in my page, but instead I found this page
http://www.codeproject.com/Articles/30588/ASP-NET-MVC-Flexigrid-sample
It looks really nice, but my question is - how current this is and do you think this is something I should try implementing?
What are you using for your interface elements?
Thanks in advance.
Friday, September 28, 2012 4:21 PM
Answers
-
User375511646 posted
Flexigrid is a good option.
I have used the same in one of my projects. It works good. You can find the sample code below. Inface this is one free alternative i found after a loat of googling.
http://mvc4beginner.com/Sample-Code/JQuery-UI/ASP-.NET-MVC-Autofill-Textbox.html
The above sample is for auto textbox using Jquery. But it contains info about flexigrid. Sample code is also available,
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, September 28, 2012 4:36 PM -
User146802239 posted
this is good and you can also use JQgrid follow this link
http://www.codeproject.com/Articles/230353/An-Example-to-Use-jQuery-Grid-Plugin-in-MVC-Part-1
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, September 29, 2012 12:38 AM -
User200755113 posted
might be helpfull for you
http://apparch.wordpress.com/2012/01/04/webgrid-in-mvc3/
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, October 17, 2012 12:04 PM
All replies
-
User375511646 posted
Flexigrid is a good option.
I have used the same in one of my projects. It works good. You can find the sample code below. Inface this is one free alternative i found after a loat of googling.
http://mvc4beginner.com/Sample-Code/JQuery-UI/ASP-.NET-MVC-Autofill-Textbox.html
The above sample is for auto textbox using Jquery. But it contains info about flexigrid. Sample code is also available,
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, September 28, 2012 4:36 PM -
User146802239 posted
this is good and you can also use JQgrid follow this link
http://www.codeproject.com/Articles/230353/An-Example-to-Use-jQuery-Grid-Plugin-in-MVC-Part-1
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, September 29, 2012 12:38 AM -
User1096912014 posted
I am afraid it's all a bit above my head at present. The sample in the first article I linked points to the site which doesn't have any FlexGrid anymore. So, I don't know if I can still use that article.
JQgrid I downloaded, but I read in the comments that the author himself switched to http://flexigrid.info/
This looks really nice, but I don't see a complete example of how to use it in a project and the short samples on that page don't really help me.
So, I am at lost as how to proceed. Do you think I should try to follow jdGrid sample and ignore author's comments?
Tuesday, October 2, 2012 5:44 PM -
User375511646 posted
Here is a complete example. Download if you have any questions send me a mail murugan@muruganad.com
Tuesday, October 2, 2012 6:47 PM -
User1096912014 posted
Thanks, this is the sample I am working on right now. First question - do we really need to make ExtensionMethods?
Also, I am using VS 2012 and MVC4.
I may contact you by e-mail if I will get stuck, thanks for the offer.
Tuesday, October 2, 2012 7:05 PM -
User375511646 posted
http://mvc4beginner.com/Sample-Code/Insert-Update-Delete/Asp-.Net-MVC-Ajax-Insert-Update-Delete-Using-Flexigrid.html
I am using two extension methods in the above sample code.
DBList = DBList.OrderBy(sortname, (sortorder == "asc"));
DBList = DBList.Like(qtype, query);
The Extension Methods are pasted below. Its not necessary to use the two extenstion methods.The Key is to return the correct JSON. It took me couple of hours to figure this out.
This is the code.
var flexgrid = new
{
page = page,
total = _DB.Category.Count(),
rows = DBList
.Select(x => new
{
id = x.CategoryName,
cell = new { x.CategoryCode, x.CategoryName }
}
)
};Remaning you can write your own logic.
public static class ExtensionMethods
{
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool asc)
{
var type = typeof(T);
string methodName = asc ? "OrderBy" : "OrderByDescending";
var property = type.GetProperty(propertyName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
return source.Provider.CreateQuery<T>(resultExp);
}
public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName, string keyword)
{
var type = typeof(T);
var property = type.GetProperty(propertyName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var constant = Expression.Constant("%" + keyword + "%");
MethodCallExpression methodExp = Expression.Call(null, typeof(SqlMethods).GetMethod("Like", new Type[] { typeof(string), typeof(string) }), propertyAccess, constant);
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter);
return source.Where(lambda);
}
}Tuesday, October 2, 2012 7:15 PM -
User1096912014 posted
Thanks. BTW, do you know what there are problems with the code display in the website? The code from your message works fine (ExtensionMethods), but the code in the link has problems with code display (<<T>> is missing, etc.).
Wednesday, October 3, 2012 12:51 PM -
User375511646 posted
Thank you. I will check and do the needfull. Did u get the code working ?
Wednesday, October 3, 2012 12:53 PM -
User1096912014 posted
Also, for Add and Edit I don't want to use inline adding/editing. I want to open a new page with the new form for Editing / Adding information.
Do you know how to adjust the script to allow the "normal" Add/Edit, but using the buttons of the FlexGrid?
Wednesday, October 3, 2012 1:11 PM -
User1096912014 posted
Not yet. Since I am trying to apply your code directly to my application, I expect I may have troubles. If you'd like, I can send you what I have so far or I will proceed for the first error.
1. I added the FlexGrid folder under Themes folder in the Content folder and FlexGrid.js directly in the scripts folder
2. I added your extension methods as is in the Models folder
3. I want to implement FlexGrid for the Clients, so I have the following Index.cshtml right now:
@model CardNumbers.Objects.Client @{ ViewBag.Title = "Clients"; } <h2>Clients Search</h2> <br /> @*<div id="progress" class ="ui-progressbar"> Loading... </div>*@ @using (Ajax.BeginForm("Search", "Client", new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "flexClients" })) { <fieldset> <legend>Search</legend> <label for="clientNo">Client No: </label> <input type="number" name="clientNo" class="numericOnly" /><br /> <label for="clientName">Client Name: </label> <input type = "text" size =25 data-autocomplete="@Url.Action("QuickSearch", "Client")" name ="clientName" /> <div> <input type="submit" value="Find / Refresh" /> </div> </fieldset> } <br /> <div style="padding-left:150px; padding-top:50px; padding-bottom:50px;"> <table id="flexClients" style="display:none"> </table> </div> <div style="display:none"> <form id="sform"> <input type="hidden" id="fntype" name="fntype"> <input type="hidden" id="ClientId" name="ClientId"> <label style="width:15px">Client # </label>: <input id="ClientNo" name="ClientNo"><br/> <label style="width:25px">Name </label>: <input id="ClientName" name="ClientName"><br /> <label style="width:25px">Contact 1 </label>: <input id="Contact1" name="Contact1"><br /> <input type="button" value="Submit" onclick="addFormData();$('#flexClients').flexOptions({ url: '/Client/Index/'}).flexReload();clearAll();$('#sform').dialog('close');"> </form> </div>
Finally, I moved the script code into the CardNumbers.js file (instead of inline) and I have there right now:
/// <reference path = "jquery-1.5.1-vsdoc.js"/> /// <reference path = "jquery-ui-1.8.11.js"/> $(document).ready(function() { $(":input[data-autocomplete]").each(function() { $(this).autocomplete({ source: $(this).attr("data-autocomplete") }); }); }); $(function () { $('input[name="delete"]').click(function () { return confirm('Are you sure?'); }); }); $(".numericOnly").keypress(function (e) { if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false; }); $("#flexClients").flexigrid({ url: '/Client/Index/', dataType: 'json', colModel: [ { display: 'Country Id', name: 'ClientId', width: 100, sortable: true, align: 'center', hide: true }, { display: 'Client #', name: 'ClientNo', width: 100, sortable: true, align: 'center' }, { display: 'Name', name: 'ClientName', width: 350, sortable: true, align: 'center' }, { display: 'Contact 1', name: 'Contact1', width: 350, sortable: true, align: 'center' }, ], buttons: [ { name: 'Add', bclass: 'add', onpress: test }, { name: 'Edit', bclass: 'edit', onpress: test }, { name: 'Delete', bclass: 'delete', onpress: test }, { separator: true } ], searchitems: [ { display: 'Client Name', name: 'ClientName' }, ], sortname: "ClientName", sortorder: "asc", usepager: true, title: 'Name', useRp: true, rp: 15, showTableToggleBtn: true, width: 700, onSubmit: addFormData, height: 200 }); //This function adds paramaters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit function addFormData() { //passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from var dt = $('#sform').serializeArray(); $("#flexClients").flexOptions({ params: dt }); return true; } $('#sform').submit(function () { $('#flexClients').flexOptions({ newp: 1 }).flexReload(); alert("Hello World"); return false; }); function test(com, grid) { if (com == 'Delete') { $('#fntype').val('Delete'); $('#ClientId').val($('.trSelected td:eq(0)').text()); $('#ClientNo').val(''); $('#ClientName').val(''); $('#Contact1').val(''); $('.trSelected', grid).each(function () { var id = $(this).attr('id'); id = id.substring(id.lastIndexOf('row') + 3); addFormData();$('#flexClients').flexOptions({ url: '/Client/Index/'}).flexReload(); }); clearAll(); } else if (com == 'Add') { $("#sform").dialog({ autoOpen: false, show: "blind", }); $("#sform").dialog("open"); $('#fntype').val('Add'); $('#ClientNo').val(''); $('#ClientName').val(''); $('#Contact1').val(''); } else if (com == 'Edit') { $('.trSelected', grid).each(function () { $("#sform").dialog({ autoOpen: false, show: "blind", width:400, height:300 }); $("#sform").dialog("open"); $('#fntype').val('Edit'); $('#ClientNo').val($('.trSelected td:eq(0)').text()); $('#ClientName').val($('.trSelected td:eq(1)').text()); $('#Contact1').val($('.trSelected td:eq(2)').text()); }); } } function clearAll() { $('#fntype').val(''); $('#ClientNo').val(''); $('#ClientName').val(''); $('#Contact1').val(''); };
I am not sure if what I am doing is correct at all. Also, as I said, I don't want to have inline Add/Edit, I want to open separate form. Can you help me with that?
Wednesday, October 3, 2012 1:22 PM -
User1096912014 posted
Sorry, I solved that error. Will be testing now.
Thursday, October 4, 2012 2:26 PM -
User1096912014 posted
I decided to test first your project (FlexGrid) because I got an error in mine on JScript in run time. With yours I also got an error in JScript
Unhandled exception at line 5, column 1479 in http://localhost:57136/Scripts/jquery.validate.unobtrusive.min.js
0x800a138f - Microsoft JScript runtime error: Unable to set value of the property 'unobtrusive': object is null or undefined
On this line:
(function(a){var d=a.validator,b,f="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function i(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function g(a){return a.substr(0,a.lastIndexOf(".")+1)}function e(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function l(c,d){var b=a(this).find("[data-valmsg-for='"+d[0].name+"']"),e=a.parseJSON(b.attr("data-valmsg-replace"))!==false;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(e){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function k(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("<li />").html(this.message).appendTo(b)})}}function j(c){var b=c.data("unobtrusiveContainer"),d=a.parseJSON(b.attr("data-valmsg-replace"));if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");c.removeData("unobtrusiveContainer");d&&b.empty()}}function h(d){var b=a(d),c=b.data(f);if(!c){c={options:{errorClass:"input-validation-error",errorElement:"span",errorPlacement:a.proxy(l,d),invalidHandler:a.proxy(k,d),messages:{},rules:{},success:a.proxy(j,d)},attachValidation:function(){b.validate(this.options)},validate:function(){b.validate();return b.valid()}};b.data(f,c)}return c}d.unobtrusive={adapters:[],parseElement:function(b,i){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=h(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});jQuery.extend(e,{__dummy__:true});!i&&c.attachValidation()},parse:function(b){a(b).find(":input[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});a("form").each(function(){var a=h(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});b.addSingleVal("accept","exts").addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.add("equalto",["other"],function(b){var h=g(b.element.name),i=b.params.other,d=e(i,h),f=a(b.form).find(":input[name="+d+"]")[0];c(b,"equalTo",f)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},f=g(b.element.name);a.each(i(b.params.additionalfields||b.element.name),function(h,g){var c=e(g,f);d.data[c]=function(){return a(b.form).find(":input[name='"+c+"']").val()}});c(b,"remote",d)});a(function(){d.unobtrusive.parse(document)})})(jQuery);
------------------------------
I opened your project in VS 2012 and it was showing 107 warning messages.
Thursday, October 4, 2012 3:32 PM -
User1096912014 posted
Ok, I got it to work in its very simple form.
Now I have several questions:
1. One of the values is returning NULL from my database and the grid also displays null. What can I do to display nothing instead?
2. How can I use the separate forms for Add/Edit buttons instead of the inline form? E.g. I'd like to use Add/Edit as if I would use it from the way MVC generates the Index View.
Thanks again for the sample.
Friday, October 5, 2012 5:47 PM -
User375511646 posted
Answer for
1. You would have to handle it before passing the value to the flexigrid. Like check if its null and try passing ""or handle it in the quiery itself.
2.For the second qn.
} else if (com == 'Add') {
$("#sform").dialog({
autoOpen: false,
show: "blind",
});
$("#sform").dialog("open");
$('#fntype').val('Add');
$('#CategoryCode').val('');
$('#CategoryName').val('');
} else if (com == 'Edit') {Insert script to open in new window. like
newwindow = window.open();
newdocument = newwindow.document;
newdocument.write(Your code here);
newdocument.close();or there are several javascripts to open new window. You could pass parameters as query script. Then call back the form file .
Friday, October 5, 2012 6:39 PM -
User1096912014 posted
I am not sure this is the answer. I want to open the new views. Also, right now I can not make it work the way I want - I want to have a search at the top and display the flexgrid with the results once I searched. I can not make it to work.
Also, I think I found a few bugs:
1. I am able to highlight multiple rows (in Google Chrome) and the Edit doesn't seem to work correctly for me.
2. The textbox for entering page number is too wide (both in width and height) and also allows to type any garbage.
Saturday, October 6, 2012 9:05 PM -
User1096912014 posted
Do you know why my Edit doesn't work - shows everything empty?
} else if (com === 'Edit') { $('.trSelected', grid).each(function () { $("#sform").dialog({ autoOpen: false, show: "blind", width: 600, height: 500 }); $("#sform").dialog("open"); $('#fntype').val('Edit'); $('#Id').val($('.trSelected td:eq(0)').text()); $('#Number').val($('.trSelected td:eq(1)').text()); $('#Name').val($('.trSelected td:eq(2)').text()); $('#Contact1').val($('.trSelected td:eq(3)').text()); });
Saturday, October 6, 2012 10:00 PM -
User1096912014 posted
I tried to contact you by e-mail before, but didn't get a reply back. I got stuck trying to implement flexgrid not by itself (as in your sample), but with some extra search controls limiting the initial display. I am wondering if you can help me with that or I better forget the flexgrid for the moment and use the way the sample 'book' applications work.
Thursday, October 11, 2012 1:12 PM -
User200755113 posted
might be helpfull for you
http://apparch.wordpress.com/2012/01/04/webgrid-in-mvc3/
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, October 17, 2012 12:04 PM -
User1096912014 posted
This is very interesting and if I would not start with flexigrid I could have looked into this instead.
Few questions:
1. Is it built-in into MVC 3 (4) or I need to install it?
2. Is it possible to have Add/Edit/Delete buttons on the side (not on every row) that will operate with the current row? Do you know example for this?
3. Is it possible to visually highlight the current row and have edit on the click?
Thanks again.
Wednesday, October 17, 2012 12:22 PM