0

I want to show the image if the item has image, and no image otherwise. Here is my code, but it gets some errors.

So how to use if condition in format parameter of webgrid?

grid.Column("Image", "Ảnh minh họa", format: (item) =>
        if(item.Image == null)
        {
            @<text>Chưa có ảnh minh họa</text>
        }
        else
        {
            @<text><img width="50" height="50" src="@Url.Content("~/images/")@item.Image" /></text>
        }
        , canSort: false)

Edit: I have solved this issue. Here is my code:

grid.Column("Image", "Ảnh minh họa", format: @<text>@if (item.Image == null) { <text>Chưa có ảnh minh họa</text> } else { <text><img width="50" height="50" src="@Url.Content("~/images/")@item.Image" /></text> }</text>
                    , canSort: false),

1 Answers1

0

Try like this:

grid.Column("Image", "Ảnh minh họa", format: (item) =>
        if((string)item.Image == null)
        {
            @<text>Chưa có ảnh minh họa</text>
        }
        else
        {
            @<text><img width="50" height="50" src="@Url.Content(string.Format("~/images/{0}",(string)item.Image))" /></text>
        }
        , canSort: false)

Edit

grid.Column("Image", "Ảnh minh họa",
   format: item.Image == null 
   ? @<text>Chưa có ảnh minh họa</text> : @<text><img width="50" height="50" src="@Url.Content(string.Format("~/images/{0}",(string)item.Image))" /></text>, 
   canSort: true)
Karthik Chintala
  • 5,465
  • 5
  • 30
  • 60
  • Hi Karthik, I try as you show but still get error: The name 'item' does not exist in the current context The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func, string, bool)' has some invalid arguments – Nguyễn Trọng Bằng Feb 22 '13 at 06:49
  • I get this error: **The name 'item' does not exist in the current context** and **The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func, string, bool)' has some invalid arguments** – Nguyễn Trọng Bằng Feb 22 '13 at 06:58
  • I try with the new code you've edited but get the same error. and new error: **Argument 3: cannot convert from 'lambda expression' to 'System.Func** – Nguyễn Trọng Bằng Feb 22 '13 at 07:04
  • what is the type of Image ? is it string type. I mean does it show the path to the file – Karthik Chintala Feb 22 '13 at 07:11
  • Yes, item.Image is a string. Can you give me a sample code with condition (if, else) in format parameter, similar my code above? – Nguyễn Trọng Bằng Feb 22 '13 at 07:15
  • Please check this [thread](http://stackoverflow.com/questions/14972848/how-to-write-if-condition-in-column-of-web-grid/14974251#14974251) – Karthik Chintala Feb 22 '13 at 07:20
  • 2
    Thank you Karthik, Finally, I have solved this issue. Here is my code: grid.Column("Image", "Ảnh minh họa", format: @@if (item.Image == null) { Chưa có ảnh minh họa } else { } , canSort: false), – Nguyễn Trọng Bằng Feb 22 '13 at 07:56