How to insert variable value into textbox using Razor in ASP.NET MVC

Here is the code for my text box in ASP.NET MVC's Razor markup language:

<div class="form-group">
    @Html.LabelFor(m => m.FullName, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.FullName, new { @class = "form-control" })

Currently, when the user first navigates to the page, the text box is empty.

However, I would like the text box to be filled with the value for m.FullName when the user first navigates to the page. How can I accomplish this?

2 answers

  • answered 2018-02-13 15:04 Tchaps

    I think that you can get the same result using this EditorFor:

      @Html.EditorFor(m => m.FullName, new { htmlAttributes = new { @class = "form-control", @value="full name here" } })

    TextBox and Editor are doing almost the same thing in this case ! I this there be not difference here !

  • answered 2018-02-13 21:37 Emilia

    The answer ended up being exactly what the commenters suggested. Specifically:

    public class MyController : Controller
        public ActionResult Edit(string id)
            // Edit the Microsoft GraphServiceClient user first ...
            // Here is where I went wrong - I didn't pass in myEditedUser
            return View("Edit", myEditedUser);

    Now in Edit.cshtml, the following line of code is the first line (note that I am using an ExtendedUser object which inherits from Microsoft.Graph.User:

    @model MyProjectName.Models.ExtendedUser

    Like the commenters suggested, I didn't have to make any changes to the @LabelFor or @TextBoxFor code, but I just needed to return myEditedUser to the View.