1

Using Razor, in the following iteration of items in a View, how can we make the CustName input readonly if CustName is not empty

@model  ABCTest.Models.ViewModels.MyViewModel
...
<table>
@for (int i=0; i<Model.CuttomersOrders.Count(); i++)
{
 <td>...</td>
...
 <td>
        @Html.EditorFor(c => c.CuttomersOrders[i].CustName)
 </td>
...
}
...
</table>

1 Answer 1

1

Conditionally call the helper method with the relevant htmlAttributes overload value.

EditorFor helper method does not have an overload which takes the htmlAttributes dictionary. So you can use the TextBoxFor helper method instead.

@for(int i=0; i<Model.CuttomersOrders.Count(); i++)
{
  <tr>
    <td>
    @if (!String.IsNullOrEmpty(Model.CuttomersOrders[i].CustName))
    {
        @Html.TextBoxFor(c => c.CuttomersOrders[i].CustName,new { @readonly=true})
    }
    else
    {
        @Html.TextBoxFor(c => c.CuttomersOrders[i].CustName)
    }
    </td>
  </tr>
}

Remember, the existence of the readonly attribute will make the input element readonly irrespective of the value. So basically the below 2 lines will render a readonly input element.

<input  readonly="False" type="text" value="Java" />
<input i readonly="true" type="text" value="Java" />
Sign up to request clarification or add additional context in comments.

3 Comments

It seems we can't do it with style attribute of <td>, correct?
your question says you want to make the input element readonly. readonly is not a valid attribute for td.
Thanks. Two points were worth noticing for me 1. Use of readonly regardless of true or false 2. Use of Model.CuttomersOrders[i].CustName in if statement. I was trying lambda expression inside String.IsNullOrEmpty(....) but VS2017 was not accepting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.