Search code examples
modelasp.net-core-mvctextarearazor-pagesviewbag

Populating textarea using ViewBag ASP.NET Core MVC


I have this textarea that is not being populated. The viewbag is not empty because if I populate a textbox instead, the information in @ViewBag.JobsDetails.job_description shows. It just does not show in a textarea

<div class="col-lg-6 mb-4">
    <label class="form-label" asp-for="job_description"></label>
    <textarea class="form-control" asp-for="job_description">@ViewBag.JobsDetails.job_description</textarea>
</div>

Solution

  • From Textarea does not display value when it has an asp-for parameter we can see:

    The behavior you're observing here is by-design. asp-for purposefully overwrites the content of the text area.

    And below are two options you can refer:

    Option 1.use name attribute not asp-for like:

    <div class="col-lg-6 mb-4">
             <label class="form-label" asp-for="job_description"></label>
             <textarea class="form-control" name="job_description">@ViewBag.JobsDetails.job_description</textarea>
       </div>
    

    Option 2.you can pass the model to the view like:

    In Controller:

    public IActionResult Index()
     {
    
         ViewBag.JobsDetails = new JobsDetails()
         {
             job_description = "Steve"
            
         };
         var model = ViewBag.JobsDetails;
         return View(model);
     }
    

    In the view:

    <div class="col-lg-6 mb-4">
             <label class="form-label" asp-for="job_description"></label>
             <textarea class="form-control" asp-for="job_description"></textarea>
       </div>
    

    result: enter image description here