WebGrid is returing an error "Column does not exist" - asp.net-mvc

I have the following web grid inside my Razor view on asp.net MVC 5 and i am using Entity framework 6.0:-
Now the web grid is working well on all the paging except for one paging, and when i checked it i found that the WebGrid will return this error:-
Column "SDUser.Department.Definition.DEPTNAME" does not exist.
So seems some items inside this page does not have those navigation properties SDUser.Department.Definition.DEPTNAME,, so how i can overcome this issue?
EDIT:- Here is my updated code, where i added If/Else but still i am getting the same error:-

Before adding new WebGridColumn in gridcolumns, you check whether DEPTNAME property is there or not.
#if(#Model.Content.FirstOrDefault().SDUser.Department.Definition.HasProperty("DEPTNAME"))
{
gridcolumns.Add(new WebGridColumn()
{
ColumnName = "SDUser.Department.Definition.DEPTNAME",
Header = Html.DisplayNameFor(model => model.Content.FirstOrDefault().SDUser.Department.Definition.DEPTNAME).ToString(),
CanSort = true
});
}
Additionally, if you want to check its value is there or empty then use this
#if(#Model.Content.FirstOrDefault().SDUser.Department.Definition.HasProperty("DEPTNAME") && #Model.Content.FirstOrDefault().SDUser.Department.Definition.GetProperty("productSalePrice").Value != String.Empty)
{
//your code
}
Note: I don't know actually your hierarchy of Model, I consider that specific page has not DEPTNAME property. (you are free to modify according to your requirement)

Related

Telerik MVC grid sort order preserve

I have an old Telerik MVC grid(not Kendo). It's sortable:
.Pageable(pager => pager.Enabled(true).PageSize(20))
.Selectable()
.Sortable()
The problem is it doesn't preserve its state after navigation or page refresh. My goal is to preserve the sort state in one session. So if the user made a sort on one of the cells he should see that sorting even if he navigates elsewhere on the page, but after he logs out/ or closes the browser it can reset. How can I achieve this?
UPDATE
if (window.sortHelper) {
sessionStorage.sortSettings = JSON.stringify(e.sortedColumns[0]);
} else {
if (sessionStorage.sortSettings != 'undefined')
e.sortedColumns[0] = JSON.parse(sessionStorage.sortSettings);
window.sortHelper = true;
}
I did this so far in the OnBeforeDataBinding event, the logic seems to be good, but it doesn't work. Doesn't makes the grid sorted despite that the sortingColumns was set.
Any idea?

Using Html.DropDownListFor and selecting a value inside the SelectList will not work together

I am working on an asp.net mvc-5 web application and i wrote the following inside my Get Edit action method to buld a dropdownlist:-
var t=await unitofwork.SkillRepository.getallSkillCategories().ToListAsync();
ViewBag.SkillCategoryID = new SelectList(t, "SkillCategoryID", "Name",skill.SkillCategoryID);
and inside the view i wrote the following:-
#Html.DropDownListFor(model => model.SkillCategoryID,(SelectList) ViewBag.SkillCategoryID,"--please select--", null)
but the above did not work together , as the current SkillCategoryID will not be selected , and i will always get "--please select--". to get this fixed i have to do one of the following:-
1)to modify my action method as follow (remove the skill.SkillCategoryID):-
ViewBag.SkillCategoryID = new SelectList(t, "SkillCategoryID", "Name");
2)or to modify my view to pass null instead of mentioning the ViewBag:-
#Html.DropDownListFor(model => model.SkillCategoryID,null,"--please select--", null)
so why my first approach did not work ??

Disable/remove Kendo mvc validator

A simple question, or so I thought.
How to disable client side validation for kendo mvc grid?
I thought there would be a property: "Enabled", "validator" or such which I could set to false but I can't find nothing.
You're correct in that there's no way to disable the validation via a property or options setting, however, you can work around it.
The validators for the grid cells are created internally by the grid. You can disable validation by replacing the functions of the validator object in the "edit" event of the grid, after it is created, i.e.:
edit: function (e) {
// Always return valid
e.sender.editable.validatable.validate = function () { return true; };
e.sender.editable.validatable.validateInput = function(input) { return true; };
}
This should have the effect of disabling validation by always returning true.
EDIT:
You might also want to replace validateInput, I've updated the code snippet.

Kendo UI Grid in MVC with Conditional Custom Command Button

I have a KendoUI Grid I'm using an MVC web application, all working fine however I want to add a custom command button that is shown conditionally in the UI and simply executes a command on my controller passing it the required parameter.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click())
The command is specified as above but I only want the button to show when the DataItems IsLocked property is true.
I also cannot figure out how to just call and method on the controller rather. I cannot find a demo of this on the Kendo site and not sure how to move this forward.
Here is a specific example for using client templates for conditional command buttons.
const string ShowUpdateButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-edit' href='\\#'><span class='k-icon k-edit'></span>Update</a>#}#";
const string ShowReverseButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-reverse' href='/JournalDetail/Reverse/#: ID #' ><span class='k-icon k-reverse'></span>Reverse</a>#}#";
const string ShowDeleteButton = "#if (IsAdjustment == true) {#<a class='k-button k-button-icontext k-grid-delete' href='\\#'><span class='k-icon k-delete'></span>Delete</a>#}#";
You can do the template inline but I find it easier (particularly for multiple buttons) if you declare constants and then use string.format to concatenate them.
col.Template(o => o).ClientTemplate(string.Format("{0}{1}{2}", ShowUpdateButton, ShowDeleteButton, ShowReverseButton));
The upside is it will work with popup editor whereas jquery hacks will ignore the conditional status when a user cancels out of edit. A cancel from the popup editor will restore the grid row from the viewmodel or wherever Kendo stores it which results in button states from before any jquery/javascript hack. The method above will also auto-wire the standard commands since I copied their HTML output for the client template.
The downside is that if Kendo changes their pattern for command buttons the client template may fail. I tired several other methods besides this one and the downside to this method seems better than the other methods.
Note on Kendo Forums: As of the date of this post, they do not appear to allow people who do not pay for support to post to the forums so I would suggest posting questions here instead. They monitor Stack Overflow and in my experience they seem to answer questions more quickly here.
Use template column instead - via the ClientTemplate method.
Conditional templates are covered here and multiple times on the forums - the Command columns is not that flexible.
As of the December 2018 release of Kendo, you can now conditionally display custom buttons more easily, but it still relies on JavaScript to do its work, this function should be defined before your dataGrid or you'll run into issues.
function showCommand(dataItem) {
console.log("determining to hide or show" + dataItem);
// show the Edit button for the item with Status='New'
if (dataItem.Status == 'New') {
return true;
}
else {
return false;
}
}
Then the code for the Grid.
.Columns (columns => {
columns.Command (
command => command.Custom ("Approve")
.Visible ("showCommand")
.Click ("approveFunc")
)
.Width (100)
.HeaderTemplate ("Actions")
})
You can control custom command button visibility by Visible property.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click().Visible("unlockAccountVisible"))
Visible property accepts JS function name and passes current dataItem as an argument.
JS function that evaluates button visibility:
<script>
function unlockAccountVisible(dataItem) {
// show the UnlockAccount button only when data item property IsLocked == true
return dataItem.IsLocked;
}
</script>
Read more in Show Command Buttons Conditionally kendo-ui documentation article.

ASP.net MVC - IE9 has an extra item with an empty key in forms collection

I have a bit of an odd problem, and I'm struggling to track down the root cause...
I have an ASP.net MVC site, and recently one of my colleagues started using IE9, and noticed a problem with one of the pages - it wasn't updating on click of save.
I figured that this would probably be a script issue, as there is a fair bit of jQuery used on this page, and it may still be, but:
If I submit this page in Chrome (or in IE8/7/6), then I get a forms collection with 11 items in it, as I would expect. If I submit the same page in IE9, I get an extra item at the end of the collection which has an empty string as key and an empty string as the value. This causes the call to UpdateModel() to not work (but not throw an exception) - none of these values are updated in my object, and the ModelState is still showing as valid.
So far, I've only found this one page, but I'm curious if anybody might know what is causing this?
Update 04/04/2011 - Narrowed down the culprit:
I removed bits of code until this worked and narrowed it down to some code in my validation. I use the jQuery validate plugin, and had the following as a submit handler (some redaction performed on names...):
submitHandler: function (form) {
var submitForm = true;
var newValue, originalValue;
newValue= $("#newValue").val();
originalValue= $("#originalValue").val();
if (newValue!= originalValue) {
//affectedValues is an array populated at the top of the page.
if ($.inArray(originalValue, affectedValues) != -1 &&
$.inArray(newValue, affectedValues) == -1) {
submitForm = confirm("Are you sure you want to do this");
}
}
if (submitForm) {
form.submit();
}
},
Removing this from the code (which I can thankfully do, as it's a bit of legacy code), seems to make this work, my empty item in the forms collection is gone. If anybody has any idea why this might have been happening, that'd be great.
Might be worth checking all the form fields in firebug to see if you have any un-named elements? I know I got caught out by the Select behaviour in IE before.
pdate 04/04/2011 - Narrowed down the culprit:
I removed bits of code until this worked and narrowed it down to some code in my validation. I use the jQuery validate plugin, and had the following as a submit handler (some redaction performed on names...):
submitHandler: function (form) {
var submitForm = true;
var newValue, originalValue;
newValue= $("#newValue").val();
originalValue= $("#originalValue").val();
if (newValue!= originalValue) {
//affectedValues is an array populated at the top of the page.
if ($.inArray(originalValue, affectedValues) != -1 &&
$.inArray(newValue, affectedValues) == -1) {
submitForm = confirm("Are you sure you want to do this");
}
}
if (submitForm) { form.submit(); }},
Removing this from the code (which I can thankfully do, as it's a bit of legacy code), seems to make this work, my empty item in the forms collection is gone. If anybody has any idea why this might have been happening, that'd be great.
I had some problems with my MVC sites due to the caching features introduced for IE9. My work around was to disable caching in my controller by adding an attribute:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class FaxController : Controller
FF, Chrome, Opera sends just value of FORM elements (button, input,..) with NAME.
IE always sends elements to server, even Submit with empty name and value which causes error.
So to be sure, always name elements.

Resources