Reputation: 2752
I want to to set text box read only if it has value in view in MVC.
So I write
<tr>
@if (model.first_name != "" ) {
<td >
@Html.LabelFor(model => model.first_name):
</td>
<td >
@Html.TextBoxFor(model => model.first_name)
<span class="required">*</span>
@Html.ValidationMessageFor(model => model.first_name)
</td>
@ else
<td >
@Html.LabelFor(model => model.first_name):
</td>
<td >
@Html.EditorFor(model => model.first_name)
<span class="required">*</span>
@Html.ValidationMessageFor(model => model.first_name)
</td>
@}
<td >
@Html.LabelFor(model => model.first_name):
</td>
<td >
@Html.EditorFor(model => model.first_name)
<span class="required">*</span>
@Html.ValidationMessageFor(model => model.first_name)
</td>
</tr>
But is is not working.. How to slove it?? How can I do it??
Upvotes: 2
Views: 1799
Reputation: 19573
You can modify your view model like the following
public class MyViewModel
{
public string first_name { get; set; }
public object first_name_attributes
{
get
{
return string.IsNullOrEmpty(first_name) ? null : new { @readonly = "readonly" };
}
}
}
In your UI, you can then add the object declaratively.
Html.TextBoxFor(x => x.first_name, first_name_attributes)
This results in a much simpler UI and the the view model has the benefit of being unit testable!
Upvotes: 4
Reputation: 6563
You can make the field readonly="readonly"
instead of disabled="disabled"
A readonly field value will be submitted to the server while still being non-editable by the user.
Upvotes: 3
Reputation: 1068
Create an if statement in razor and have a disabled = "disabled" on the input/editor that you want to disable.
@if
(model.first_name != null)
{
<td >
@Html.LabelFor(model => model.first_name):
</td>
<td >
@Html.TextBoxFor(model => model.first_name)
<span class="required">*</span>
@Html.ValidationMessageFor(model => model.first_name)
</td>
}
else
{
<td >
@Html.LabelFor(model => model.first_name):
</td>
<td >
@Html.EditorFor(model => model.first_name, new { disabled = "disabled", @readonly = "readonly" }))
<span class="required">*</span>
@Html.ValidationMessageFor(model => model.first_name)
</td>
<td >
@Html.LabelFor(model => model.first_name):
</td>
<td >
@Html.EditorFor(model => model.first_name)
<span class="required">*</span>
@Html.ValidationMessageFor(model => model.first_name)
</td>
</tr>
}
Upvotes: 1