Search code examples
htmlasp.net-mvcrazor-pages

ASP.NET get a session value inside the textbox


In my application there is a login for each admin and only that admin can add or edit employees in that department. So I save the departmentID of administrator in session from LoginController. I want to keep the departmentID read only value in the text box when try to add new employee. But departmentId always show 0.

<div class="form-group">
    @Html.LabelFor(model => model.departmentID, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.TextBoxFor(model => model.DepartmentID, new { @class = "form-control", @value = Session["departmentID"], @readonly = "readonly" })
        @Html.ValidationMessageFor(model => model.DepartmentID)
    </div>
</div>

So I thought session value is not retrieving and inserted this line above the textbox and it showed departmentID properly. <p class="form-control-static">@Session["departmentID"]</p>

How can I make the departmentID show in the textbox and readonly. If I remove readonly I can enter the departmentID value and save new record.


Solution

  • It is not working as the value of model.DepartmentID is overwriting the value attribute.

    Approach 1

    Instead, assign the value to the DepartmentID property of your model.

    public ActionResult Index()
    {
        Session["departmentID"] = /* value */;
    
        return View(new LoginModel
        {
            DepartmentID = Convert.ToInt32(Session["departmentID"].ToString())
        });
    }
    

    So in the view, it will bind the value from the ViewModel and you don't need to set the value attribute:

    @Html.TextBoxFor(model => model.DepartmentID, new { @class = "form-control", @readonly = "readonly" })
    

    Approach 2

    Otherwise, you should use Html.TextBox() which is not strong-typed. You can refer to Html.Textbox VS Html.TextboxFor for the difference.

    @Html.TextBox(nameof(Model.DepartmentID), 
        Convert.ToInt32(Session["departmentID"]), 
        new { @class = "form-control", @readonly = "readonly" })
    

    Note that, Approach 2 will bind the Session["departmentID"] value to the text field. But if you are assigning the value to the DepartmentID property, the DepartmentID's (property) value will not bind to the text field.