Punya Munasinghe
Punya Munasinghe

Reputation: 285

How to get current logged users email address to the value attribute in @Html tag in razor view?

I'm using ASP.NET C# with entity framework to build a website. In here I'm managing a user profile also. So i want to edit my profile details according to the logged user's email address. But email is the primary key and i don't want to give it for editing. I want to keep email text-field as non-editable field and need to visible email of the current logged user in there. So for that i have coded that email part in my Profile.cshtml file as follows.

@Html.TextBoxFor(model => model.Email, new { @class = "form-control", disabled = "disabled" , **Value = "Session['UserEmail'].ToString()"**})
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

But the above highlighted part will not give me the email to the text field. Instead of that it will display the Session['UserEmail'].ToString() this as it is after rendering. I don't know how to fix this problem.

Upvotes: 0

Views: 301

Answers (1)

Liam
Liam

Reputation: 29754

You need to populate the value in your model, don't try and override the value in the view:

Controller

public ActionResult MyAction()
{
   var myModel = new MyModel() {Email = Session['UserEmail'].ToString();}
   return View(myModel);
}

View:

@Html.TextBoxFor(model => model.Email, new { @class = "form-control", disabled = "disabled"})
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

i.e. don't put Value = "Session['UserEmail'].ToString()" above. It won't work. the Model holds the data, the view simply renders this data

Upvotes: 1

Related Questions