Mvc 3 texbox in webgrid (razor)
Solution 1
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: <input type="text" name="LastName" value="@item.LastName" /> // avoid extensions
Also, I believe there's an inherent lambda with an "item" parameter - you shouldn't need to declare this yourself.
Solution 2
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.
Solution 3
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>
Solution 4
Try this:
grid.Column(format: (item) => Html.TextBox("LastName", (object) item.LastName))
user408698
Updated on July 20, 2022Comments
-
user408698 almost 2 years
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>
-
user408698 over 13 yearsThere most be a easier way a doing it.
-
Darin Dimitrov over 13 years@user408698, I hope there is but I am a bit skeptical.
-
user408698 over 13 yearsI have taking the question to the blog of the presenter of the code I am modifying (Shiju Varghese). I think we need so guidance on best practice.
-
Boris B. about 13 yearsUsing this approach, when that form with textboxes is submitted back to a HttpPost action, how do you know which value belongs to which record?
-
Darin Dimitrov about 13 years@Boris B, you could include an additional hidden input containing the record id.
-
Boris B. about 13 yearsI guess that means something like
hidden id="RowId{N}" <=> textbox id="LastName{N}", N=1..RowCount
. Thank you. -
iProgrammer over 4 yearsi want to add dynamic textbox column with this bt it is not editable..ie i m unable to enter any value in this textbox
-
Skanda over 4 yearsHow to save the values from the textbox column in webgrid to a table in the database.