Chris Chris - 1 month ago 19
ASP.NET (C#) Question

How can I access model property inside viewmodel using asp-for?

I have this model

public partial class MtbWarehouse
{
public int Idhwarehouse { get; set; }
public string Namewh { get; set; }
}


I implement the model in this view model

public class WarehouseViewModel
{
public MtbWarehouse Warehouse { get; set; }
public string ListAction { get; set; } = "Index";
}


And I am using WarehouseViewModel in view

@model ViewModel.warehouseviewmodel
<input type="text" asp-for="Warehouse" class="form-control" placeholder="">


How can I access
Namewh
using
asp-for
because this asp-for thing is better than using

@Html.TextBoxFor()

Answer

If you are after rendering an input text element for Namewh property of the Warehouse property of your view model, you can use the dot notation to access a child properties' property. Like this

<form asp-action="Index" asp-controller="Home">   
    <input type="text" asp-for="Warehouse.Namewh" />
    <input type="submit"/>
</form>

This will generate an input text element with name Warehouse.Namewh and will render the value of that property if you set that from your GET action method.

VS Intellisense may still show this as invalid with red color. But when this code is executed, the tag helper will generate the correct input field with the value