The title might be confusing, so here is my problem: I'd like in my View a readonly textbox only if my Action is for editing (something like EditLocation) and if my Action is intended for adding a new record (AddLocation), I'd like an editable textbox.
My ff. code works, but I was wondering if there's a "cleaner" solution
@using (Html.BeginForm(Model.Location.Id == 0 ? "AddLocation" : "EditLocation", "Location"))
{
<fieldset>
@Html.HiddenFor(x => x.Location.Id)
@Html.HiddenFor(x => x.Location.CompanyGroupId)
@Html.HiddenFor(x => x.CompanyGroup.Id)
@Html.HiddenFor(x => x.CompanyGroup.Code)
<div class="form-group">
<strong><span>@ResourcesCommon.Location_Code</span></strong>
@if (Model.Location.Id == 0)
{
@Html.TextBoxFor(x => x.Location.Code, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Location.Code)
}
else
{
@Html.TextBoxFor(x => x.Location.Code, new { @class = "form-control", @readonly = "readonly" })
@Html.ValidationMessageFor(x => x.Location.Code)
}
</div> ...
Thanks and have a good week ahead!
This might help you:
@Html.TextBoxFor(x => x.Location.Code, new Dictionary<string, object>()
.AddIf(true, "@class", "form-control")
.AddIf(Model.Location.Id != 0, "@readonly", "readonly"))
// This returns the dictionary so that you can "fluently" add values
public static IDictionary<TKey, TValue> AddIf<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, bool addIt, TKey key, TValue value)
{
if (addIt)
dictionary.Add(key, value);
return dictionary;
}
I took it from another stackoverflow post long back which i don't have the link.