简体   繁体   中英

ASP.NET Core -> Label asp-for not returning label text

For some reason I can not get my label to render it just displays the text box. I am new to programming and .NET Core. I reckon this is a simple of mistake of mine. I just cant see it. Any ideas please?

Model

namespace Web.Models
{
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ItemType ItemType { get; set; }
        public string MapCode { get; set; }
    }
}

Controller

public ViewResult Create()
{
    return View();
}

View

@model Web.Models.Item
    
<div class="container">
    <form asp-action="NewRecord" method="post" class="form-group" role="form">
        <div class="form-group row">
            <label asp-for="Item.Name"></label>
            <div class="col-md-5">
                <input asp-for="Item.Name" class="form-control" placeholder="Name" />
            </div>
        </div>
    </form>
</div>

在此处输入图像描述

In your view if you set explicitly model then you only need to put name of property from that model. That means your view should looks like following code and you don't need and you cannot explicitly put Item.Name :

@model Web.Models.Item

<div class="container">
<form asp-action="NewRecord" method="post" class="form-group" role="form">
    <div class="form-group row">
        <label asp-for="Name"></label>
        <div class="col-md-5">
            <input asp-for="Name" class="form-control" placeholder="Name" />
        </div>
    </div>
</form>

On other side if you want to use some custom name you should use annotations:

using System.ComponentModel.DataAnnotations;

Hovewer, probably here you want to use View Models instead directly Models then you need some UI validation, custom names etc. Follow this example and try to understand logic.

public class Item
{
    public int Id { get; set; }

    [Display(Name = "Some name")]
    public string Name { get; set; }

    [DisplayName("Map code")]
    [MaxLength(30)]
    public string MapCode { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM