Ach113
Ach113

Reputation: 1825

How to populate textboxes in ASP.NET MVC

I want to show user's name and email in a HTML textbox. How can I provide value to the textbox from the controller?

I have tried this but it gives me Null Reference Exeption:

@model NamespaceName.Models.Account
<input class="contact" type="text" name="your_email" value="@Model.Email" /></p>

Upvotes: 0

Views: 1332

Answers (2)

Hien Nguyen
Hien Nguyen

Reputation: 18973

Null Reference Exeption because of your Model object is null. You need pass Model from Controller.

In your controller

ActionResult YourAction(){
      //handle code to get Account
      var account = new Account();
      return View(account);
}

And in view cshtml you can use

@model NamespaceName.Models.Account
<input class="contact" type="text" name="your_email" value="@Model.Email" /></p>

Upvotes: 1

evilGenius
evilGenius

Reputation: 1101

Tag Helpers to the rescue New to ASP.NET Core is the concept of tag helpers which let you easily bind your HTML elements to properties on your ViewModel.

Here’s the simplest code we could possibly write to show our ViewModel’s values in input boxes…

<h2>User Profile</h2>

<input asp-for="Name" />
<input asp-for="Email" />

Preview this in the browser and there you have it… enter image description here

Upvotes: 1

Related Questions