Reputation: 10402
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
Upvotes: 0
Views: 13734
Reputation: 11
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.
Upvotes: 1
Reputation: 20792
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
Upvotes: 1
Reputation: 7200
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()));
}
Upvotes: 0