Chris Chris - 7 months ago 55
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
because this asp-for thing is better than using



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"/>

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