Question

I'm doing some practice with MVC4. My practice project is a simple kind of comment board/forum that allows both registered users and anonymous users to post comments.

Currently, I have my code set up so that even registered users can enter whatever name they'd like when submitted a small name + message form. What I'd like to have is to disable this behavior for registered users, instead using their username taken from their login information.

Ideally, registered users will have name box already have their username loaded in it and be uneditable. This username will then be used when the form goes through validation which makes sure neither the name nor message is empty.

Here is my code from the view:

<div class="editor-label">
        @Html.LabelFor(x => x.comment.Name)
    </div>
    <div class="editor-field">
        @Html.ValidationMessageFor(x => x.comment.Name)
        <br />
        @if (User.Identity.Name=="") {
            @Html.EditorFor(x => x.comment.Name)
        } else {
            @Html.EditorFor(x => x.comment.Name, Model.PosterName)
        }
    </div>

Note that Model.PosterName just holds the user's username as a string. It is not null or empty.

How can I go about editing the second EditorFor line so that uses the Model.PosterName as a default option? Should I perhaps be using a DisplayFor instead for the uneditable behavior?

The code I have written above does not populate the EditorFor with any values whatsoever.

Thanks!

Was it helpful?

Solution

The model you pass into the view for a new comment should have comment.Name set to what ever value you want. You can do that in your controller. If you can post your controller code, I'll be able to give you the exact code you need to add.

If you want to disable this input field in your view, do this:

@Html.TextBoxFor(x => x.comment.Name, new { @disabled = "disabled" } )

You don't need to use EditorFor if you know it's a text box. Using TextBoxFor enables you to specify html attributes like above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top