How to fill an EditorFor as the username of the logged in user

1

I have a View , where the user must fill some fields, and have a last field that I left it disable , and I would like this field to appear the user name, however how do I fill in?

Model :

public class CombustivelModels
{
    [Key]
    public int CombustivelId { get; set; }

    [Required]
    public decimal km_inicial { get; set; }
    [Required]
    public decimal km_final { get; set; }
    [Required]
    public decimal litros { get; set; }
    [Required]
    [DataType(DataType.Currency)]
    public decimal valor { get; set; }

    [Required]
    public string UserId { get; set; }
}

View :

        <div class="form-group">
             @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })
             <div class="col-md-10">
                @Html.EditorFor(model => User.Identity.Name, new { htmlAttributes = new { @class = "form-control", @disabled=""} })
                @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
             </div>
        </div>

Example:

Butwhentryingtosave:

    
asked by anonymous 30.11.2016 / 19:05

1 answer

1

When you put an annotation of [Required] and use EditFor it will create the imput with data-val="true" that will already do this validation for you.

When you made @Html.EditorFor(model => User.Identity.Name, it generated an Imput with no name other than UserId ...

Since there is no imput in the form with the name of UserId it will try to validate and will not be able to bind this property of its VM object and will put the message on the screen ...

This message appears where you made @Html.ValidationMessageFor(model => model.UserId,

What I would do in this case would be to just display its name in an imput by picking up with User.Identity.Name and not having this property in the register VM.

On the server side you get the logged in user and play in the database (I believe it's a CRUD you're doing).

If I could not heal the doubt, tell me that I'm better.

UPDATE

In your Model you take the annotation as below:

From:

    [Required]
    public string UserId { get; set; }

To:

    public string UserId { get; set; }

In the view you remove:

@Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })

In the controller I believe you are getting a CombustivelModels and with the changes I suggested it will be filled, but with the UserId null property

In the controller code you get the user name and play on the property.

meuObjQueVeioDaView.UserId = User.Identity.Name
//....
//resto do código

Just confirm that User.Identity.Name will work on the controller, I think it will, if you can not tell me.

    
30.11.2016 / 19:21