Brian
Brian

Reputation: 1823

ASP.NET MVC4 Table with one column that is the primary key

I'm using:

I've got a table Role:

Role table

(One column that's called RoleName, datatype varchar(50) and is the primary key)

When I create a strongly-typed view with as model class Roles (extra 's' is caused by pluralisation, no issue) and scaffold template Edit, the result is that I only get a hidden field and no edit/input field, as shown below:

<fieldset>
    <legend>Role</legend>

    @Html.HiddenFor(model => model.RoleName)

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>

This is likely due to the only column being the primary key which MVC uses to identify the database record.

I want to be able to edit every Role's RoleName. How can I make an edit page for a table with one column that is the primary key?

Upvotes: 0

Views: 753

Answers (1)

Tommy
Tommy

Reputation: 39807

Just adjust the scaffolded HTML markup to fit what you need. You are correct that MVC made that hidden because it is a primary key. Unhide it.

<fieldset>
    <legend>Role</legend>

    @Html.TextBoxFor(model => model.RoleName)

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>

However, and this may just be subjective, I think having an int based primary key will go a long ways in doing things like:

  1. Not having a DB exception thrown if you accidentally edit or add a role name that matches an existing role name.
  2. Save space in your DB when you go to attach users to roles. Instead of having a varchar(50) duplicated for each user/role, you will only have an int duplicated. (UserId / RoleId)
  3. Quicker/better indexing on integers than varchars

Upvotes: 2

Related Questions