Reputation: 438
I'm new to MVC/C# and have the following code in a CSHTML file. Basically it determines the operation being performed (insert or update) and based on the the result decide whether the field should be displayed read-only or editable.
@if (Model.DatabaseOperationFlag == DatabaseOperation.Update)
{
@Html.TextBoxFor(model => model.BmUnit.BMU_ID, new {@readonly = "readonly"})
}
else
{
@Html.EditorFor(model => model.BmUnit.BMU_ID)
}
The code is going to be needed throughout the app but I am unsure where/how I can write some sort of control so I can use code similar:
@Html.ReadOnlyOnUpdate(model => model.BmUnit.BMU_ID, model.DatabaseOperation);
The ReadOnlyOnUpdate would then do the logic in the first code section.
Thanks in advance
Chris
Upvotes: 1
Views: 109
Reputation: 430
You could create a helper that would do that for you. Create a class with a method that extends off of HtmlHelper:
public static class Helpers
{
public static IHtmlString ReadOnlyOnUpdate(this HtmlHelper helper, int BMU_ID, DatabaseOperation operation)
{
var attrs = new Dictionary<string, object>();
if (operation == DatabaseOperation.Update)
{
attrs.Add("readonly", "readonly");
}
return helper.TextBox("BMU_ID", BMU_ID, attrs);
}
}
Through the use of generics, you could probably setup an extension method that you could do if off the model and the BMU_ID specifically. Create something similar to EditorFor:
public static IHtmlSTring ReadOnlyOnUpdateFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<TModel, TProperty>> expression, DatabaseOperation operation)
You would just have to replace TModel with your model type and TProperty with the type of BMU_ID I believe.
Hopefully this helps.
Upvotes: 1