Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvc 3 texbox in webgrid (razor)

Simple Q:How do you I get the textbox to show the value. Code below fail on item.LastName

@model List<Mvc2010_11_12.Models.Employee>
@{
    var grid = new WebGrid(source: Model,defaultSort: "FirstName",rowsPerPage: 3);
}

<div id="grid1">
    @grid.GetHtml(columns: grid.Columns(
        grid.Column("LastName"),
        grid.Column(format: (item) => Html.TextBox("LastName", item.LastName))
    ))
</div>
like image 936
user408698 Avatar asked Nov 16 '10 14:11

user408698


4 Answers

Extension methods (i.e., Html.TextBox) don't work well with dynamic objects (i.e., item)... it's a limitation of c#.

You've got a few options:

format: InputExtensions.TextBox(Html, "Last Name", item.LastName) // static call

format: Html.TextBox("Last Name", (object)item.LastName) // cast as non-dynamic object

format: &lt;input type="text" name="LastName" value="@item.LastName" /&gt; // avoid extensions

Also, I believe there's an inherent lambda with an "item" parameter - you shouldn't need to declare this yourself.

like image 139
chenriks Avatar answered Oct 08 '22 09:10

chenriks


Quite convoluted but works:

@helper TextField(Employee employee, HtmlHelper<IEnumerable<Employee>> html)
{
    @html.TextBoxFor(x => employee.LastName)
}

<div id="grid1">
    @grid.GetHtml(columns: grid.Columns(
        grid.Column("LastName"),
        grid.Column(format: item => TextField(item.Value, Html))
    ))
</div>

Maybe there's a better approach though. Still learning the Razor syntax and quite frankly I am a bit disappointed by the WebGrid helper after having used MVCContrib Grid.

like image 23
Darin Dimitrov Avatar answered Oct 08 '22 09:10

Darin Dimitrov


That one works for me

@model List<Mvc2010_11_12.Models.Employee>
@{
    var grid = new WebGrid(source: Model,defaultSort: "FirstName",rowsPerPage: 3);
}

<div id="grid1">
    @grid.GetHtml(columns: grid.Columns(
        grid.Column("LastName"),
        grid.Column(format: @<span>@Html.TextBox("LastName",@item.LastName as object)</span>   )
    ))
</div>
like image 25
Serguzest Avatar answered Oct 08 '22 09:10

Serguzest


Try this:

grid.Column(format: (item) => Html.TextBox("LastName", (object) item.LastName))
like image 28
kmattso Avatar answered Oct 08 '22 09:10

kmattso