I am in the process of learning some ASP.NET and now I have a problem that is not helping me despite intensive searching...
I have a view in which I generate a textbox (See My View): Basically, no value is displayed in the text box... even with “@Value = ‘Example’ it remains empty... However, the property @databaseSetup.DatabaseName contains “Test Database”.
Does anyone have any advice on what I am doing wrong?
My View:
@using TestProject.Models
@model DatabaseSetup;
@{
DatabaseSetup databaseSetup = new();
}
<h1>Database Setup</h1>
@using (Html.BeginForm("DatabaseSetup", "Administration", FormMethod.Post))
{
<span>Database-Name:</span>
@Html.TextBoxFor(
databaseSetup => databaseSetup.DatabaseName,
new
{
@Value = databaseSetup.DatabaseName ?? "127.0.0.1",
placeholder = "PLACEHOLDER"
}
)
My Controller: namespace TestProject.Controllers { public class AdministrationController : Controller {
public ActionResult DatabaseSetup()
{
return View();
}
[HttpPost]
public ActionResult DatabaseSetup(DatabaseSetup u)
{
return View(u);
}
}
}
My Model: namespace TestProject.Models { public class DatabaseSetup { public string DatabaseName { get; set; } = "Test Database"; } }
Even if I proceed in this way, the text box remains empty i.e. the placeholder is displayed...
@Html.TextBoxFor(
databaseSetup => databaseSetup.DatabaseName,
new
{
@Value = "Write something",
placeholder = "PLACEHOLDER"
}
)
Model-binding in asp.net-core is not simply searching everywhere for model. It maps the http request data through actions. So in your code you are binding a model initialized in view instead of passed from controller.
Html-Helper works like Tag-Helper that they both retrieve data from model state first. So even if your properties is not empty in the view, it is empty in the model state. https://www.exceptionnotfound.net/modelstate-values-override-model-values-in-htmlhelpers/ https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-8.0#the-input-tag-helper
You need to pass the data from controller to make it work.
@Html.TextBoxFor(
model => model.DatabaseName,
new
{
//Value = "Write something",
placeholder = "PLACEHOLDER"
}
)
Controller
public IActionResult DatabaseSetup()
{
DatabaseSetup model = new DatabaseSetup();
return View(model);
//return View();
}