In my project I have the requirement where certain fields depending of a certain condition should be editable or just readonly.
So I though that doing this for every field was an overkill
@if (Model.CanEdit)
{
@Html.TextBoxFor(model => Model.Foo, new { width = "100px" })
}
else
{
@Html.TextBox(model => Model.Foo, new { width = "100px", @readonly = "readonly"})
}
I decided to use an editor template, but then I realised that the width cannot be fixed, so I was wondering what’s the best way to send parameters to an Editor template? Also it should handle the scenario that width may not be defined and not use the width property at all. I found that ViewData may help with this, but having a code that looks like this makes me feel I’m doing something wrong.
@inherits System.Web.Mvc.WebViewPage<string>
@if (Model.CanEdit)
{
@if(ViewData["width"] == null)
{
@Html.TextBox("", Model, new { width = ViewData["width"].ToString() })
}
else
{
@Html.TextBox("", Model)
}
}
else
{
@if(ViewData["width"] == null)
{
@Html.TextBox("", Model, new { width = ViewData["width"].ToString() , @readonly = "readonly"})
}
else
{
@Html.TextBox("", Model, new {@readonly = "readonly"})
}
}
I wonder if there could be a way to create a helper so I could make something like:
@MyTextBoxFor(model => Model.Foo, true) @* true would be or readonly *@
@MyTextBoxFor(model => Model.Foo, true, 100) @* 100 would be the width length *@
kapsi’s answer is great, but if you want to use your helper in a strongly typed view, here’s the basic syntax. It’s a little sloppy, but you can add overloads as you see fit.
Of course, this way, you’re afforded the ability to strongly type your view elements
and
etc