1

I have the scenario where i will be adding two attribute.

One is dynamic i.e readonly based on user role & another is static i.e id

I tried this below but it is not working for me.

The attribute rendered in HTML for below is

readonlystr = , id = 'emp-name'

var readonlystr = (Model.Role.EmpEdit) ? "" : "readonly=readonly";

@Html.TextBoxFor(m => m.Name, new { readonlystr, @id = "emp-name" })
@Html.TextBoxFor(m => m.Age, new { readonlystr, @id = "emp-age" })
@Html.TextBoxFor(m => m.City, new { readonlystr, @id = "emp-city" })

Any suggestion to achieve this by combining two attributes and pass it?

2 Answers 2

1
var readonlystr = Model.Role.EmpEdit ? new Dictionary<string, object>() : new Dictionary<string, object> { { "readonly", "readonly" } };

@Html.TextBoxFor(m => m.Name, readonlystr.Union(new Dictionary<string, object>{{"id", "emp-name"}}).ToDictionary(x=>x.Key, x=>x.Value))
Sign up to request clarification or add additional context in comments.

Comments

0
    @{
        Dictionary<string, object> attribs = new Dictionary<string, object>();
        if (!Model.Role.EmpEdit) {
            attribs.Add("readonly", "readonly");
        }
        attribs.Add("id", "");
    }

    @{attribs["id"] = "emp-name";}
    @Html.TextBoxFor(m => m.Name, attribs)
    @{attribs["id"] = "emp-age";}
    @Html.TextBoxFor(m => m.Age, attribs)

Comments

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.