Html.DisplayFor in mvc webgrid - c#

Using an asp.net mvc webgrid, is it possible to render a column using Html.DisplayFor for the current row/column?
grid.Column("Roller", "Roller", canSort: true, format: #<text>#Html.DisplayFor( <the row result here> )</text>)
The Html.DisplayFor(m) helper uses the page model, not the current row item. Is there a way around this.
Thanks
// Johan

Yes, it is possible. For an example, consider you are binding a list of Banner objects to your WebGrid. Also consider the Banner.Active property, which is a boolean value that you want to be rendered as a CheckBox. You can do this:
format: (item) => { var banner = item.Value as Banner;
return Html.DisplayFor(modelItem => banner.Active);
}
You could also do this:
format: (item) => Html.DisplayFor(modelItem => ((item as WebGridRow).Value as Banner).Active)
But I would consider the first option more readable.

try this
var grid = new WebGrid(Model);
than do
grid.Column("Roller", "Roller", canSort: true, format: #<text>#Html.DisplayFor(modelItem => item.blabla)</text>)
Using item.blabla"whatever ur item name is" may work but im not really experienced about this.
also there is not much difference between
#<text>#Html.DisplayFor(modelItem => item.blabla)</text>
&
#<text>#item.blabla</text>
both usage does the job.

Related

To display active and inactive instead of true or false in MVC

I am new to MVC and I have one doubt regarding how to change the name of column from true and false to active and inactive. As the column data type is of bit. Below is the code and I am displaying the record in web grid using repository.
grid.Column("IsDeleted",header: "Deleted",canSort:false)
Please help.
grid.Column(header: "Deleted",
format: item =>
{
return item.IsDeleted ? "In-Active" : "Active";
})

WebGrid filtering in ASP 4.5 MVC5 - Best practice

I'm quite new to asp .net and I'm working with a WebGrid in MVC5 and I've created the folowing code in my strongly typed view:
#{
var grid = new WebGrid(Model.CustomerArticles, defaultSort: "Name");
}
#grid.GetHtml(columns: new[]{
grid.Column("ArticleNr", "ArtikelNr"),
grid.Column("Name", "Namn"),
grid.Column("Category", "Kategori"),
grid.Column("CustomerArticleNr", "Kundens artikelNr"),
grid.Column("InventoryCount", "Inventerat antal"),
grid.Column("WasSyncronized", "Synkroniserades"),
grid.Column(
header: "Action",
format: #<text> #Html.ActionLink("Ta bort", "RemoveArticle", "Article", new { id = Model.SelectedID, articleId = item.ID }, null) </text>)
})
It's working fine and it's currently possible to filter by clicking the columns but I wonder if there is any simple solutions to filtering it futher? Like for example as the aspx gridview: http://csharpdotnetfreak.blogspot.com/2011/04/gridview-filterexpression-dropdownlist.html
Is there any equivalient or any other biolerplate implementations that aren't to complicated to implement?
The important thing with my solution is to make it simpler to work with the grid if there is a lot of data in it. Which I believe it not the current situation. So other suggetions to make is clearer is also welcome.

How to reset DropDownList Index

Im using vs'12 , C# asp.net MVC-4 - Internet Template, with KendoUI EF Code First
Logic + Question: I have first and 2ndary DropDownLists (cascading ones). So many (2ndarys) will cascade off one ( main ) DropDownList. My goal is to , with script or kendo events to On main selected index change, change all other kendo DDL's back to index(0) The cascading and enabling and all of that works fine, when i switch to another control, they all empty out, but if i were to switch back they retain there values. This is not ideal for my application
need to know
Main Kendo Control
#(Html.Kendo().DropDownListFor(m => m.Tracts)
.Name("Tracts")
.HtmlAttributes(new { style = "width:300px" }) //, id = "clients"})
.OptionLabel("Select Tract...")
.DataTextField("TractName")
.DataValueField("TractID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeTracts", "ImageView");
});
})
2ndary Kendo Controls
#(Html.Kendo().DropDownListFor(m => m.LeaseholdA)
.Name("LeaseholdA")
.HtmlAttributes(new { style = "width:300px" })
.OptionLabel("Select LeaseholdA...")
.DataTextField("LeaseholdA")
.DataValueField("LeaseholdAID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetLeaseholdA", "ImageView")
.Data("filterFromTracts");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("Tracts")
)
Attempts
1 + 2 just tryed the 2 rimmed out section
function TractSelect(e) {
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
//dropdownlist.SelectedIndex(0)
dropdownlist.enable(false);
};
The selectedindex(0) attempt did what it was supposed to off the ( change event ) the select even would claim selectedIndex doesn't exist
The enable worked but when i switched back they remembered where they were. so this was ineffective
Try to use the .value property of the DropDownList(kendo)
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
dropdownlist.value(0);
These 2 lines work great
Hope this helps
the dropdownlist variable has a jquery wrapped element here
try using the below code at the same place
function TractSelect(e) {
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
dropdownlist[0].selectedIndex = 0; //Code you need to change
dropdownlist.enable(false);
};
This will make sure that you have a html element as in plain simple javascript and YES SelectedIndex is definitely not a function but property of the HTML element
I believe you should be able to set the index to 0 using the following:
$("#LeaseholdA").val(0);
This should set the dropdown to the element with a value of 0 and thus the index.
Or you can use
$("#LeaseholdA").prop('selectedIndex', 0);

ASP.NET MVC 3 use C# code in cshtml file

I'm a little new to ASP.NET MVC3.
I have this code in a cshtml file
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
tableStyle: "grid",
headerStyle: "header",
rowStyle: "row",
footerStyle: "footer",
alternatingRowStyle: "altRow",
columns: grid.Columns(
grid.Column(header: "", format: #<text><input name="Checked" type="checkbox" value="#item.Key" /></text>, style: "CheckboxColumn", canSort: true),
grid.Column("Name", "Name"),
grid.Column("Address", "Address"),
grid.Column("City", "City"),
grid.Column("PhoneNumber", "Phone Number"),
grid.Column("", format: (item) =>
{
if (item.ID.Length > 0)
{
//CODE GOES HERE
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\" class=\"ToolTip\" title=\"ID # {1} <br> \" /></text>", Url.Content("~/images/coupled.png"), #item.ID.ToString()));
}
else
{
return Html.Raw("<text></text>");
}
}),
))
What I want is to write a C# Code at the //CODE GOES HERE section. in order to change the Url.Content("~/images/coupled.png")
epending on item ID.
So basically I want something like:
string URLOfPic;
if(item.ID > 1000)
{
URLOfPic="~/images/aaa.png
}
else
{
URLOfPic="~/images/bbb.png
}
and finally to use Url.Content(URLOfPic)
So how can I use that C# code in the page?
I hope I was clear.
Thank you very much for any help
PS: I want it to be a C# code and not a javascript or anything else.
In normal ASP.NET I can just use the code behind to do it. but in MVC3 I have no idea how
Being new to Asp.net mvc let me give you some advice, Don't Do That! The most code you should have in a view is a for loop, all of that kind of logic should be done in the action.
basically take your data and do all logic and formatting in the action and add it to a view model then pass that to the view. Other wise your going to create very brittle code blocks that won't error until run time
Modify your item class to add an image class. In the image class you can add Image.URL, Image.Title. This way in the controller you can assign the item an image based on it's ID. This will also allow you to more easily modify the image URLs at a single point of code, instead of modifying in every view that you use this logic in.
I think you are close, did this not work?
if (item.ID.Length > 0)
{
string URLOfPic;
if(item.ID > 1000)
{
URLOfPic="~/images/aaa.png";
} else {
URLOfPic="~/images/bbb.png";
}
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\" class=\"ToolTip\" title=\"ID # {1} <br> \" /></text>", Url.Content(URLOfPic), #item.ID.ToString()));
}

MVC3 Dynamic List Views

In MVC3, I've been able to rely on Html.DisplayForModel() to generate display's for my data. Using this method, and various templates, I have a single View for displaying several of my Models. What I'm wondering though, is there a way I can get this to work on Lists for my models?
For example, I have a model called Networks. My view to list out multiple networks looks like this:
#model PagedList<Network>
<div id="networkList">
#Html.Grid(Model).Columns(column => {
column.For(x => Html.ActionLink(x.Id.ToString(), "NetworkDetails", new { id = x.Id })).Named("Network ID");
column.For(x => x.Name);
column.For(x => x.Enabled);
}).Attributes(Style => "text-align: center")
#Html.AjaxPager(Model, new PagerOptions() { PageIndexParameterName="page", ShowDisabledPagerItems = false, AlwaysShowFirstLastPageNumber=true },
new AjaxOptions() { UpdateTargetId = "networkList" })
</div>
I'm wondering if it is possible to use a single template when generating lists for my models. I could rely on attributes to know which properties I would like to generate in my list, ie: [ListItem].
The head scratcher for me is, how can I pass a dynamic model to an extension method? If it's of any help, the Html.Grid extension is from MVCContrib. Has anyone else done something similar? It would be great to rely on a template as it would really chop down on the amount of code.
You can achieve it for EditorFor() using the following (it might be similar with your Grid extension method assuming it can take the template name parameter):
// in the main view
#Html.EditorFor(o => o.InvoiceId, "TemplateName", new { Property = "InvoiceId" })
#Html.EditorFor(o => o.Title, "TemplateName", new { Property = "Title" })
// in the template view
#model object
#{ var property = (string)this.ViewData["Property"]; }
Alternatively you can just pass in the name of the template and use this code in the template
var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
if (prefix.EndsWith("InvoiceId")) { ... }

Categories