简体   繁体   中英

Razor Pages Using Html.EditorFor() to Edit / Create

Complete Noob here - trying to learn Dot Net Core 2 Razor Pages. Was trying to figure out how to do "down and dirty" editing on some of my models. Was going to try to use reflection, but that wasn't working - or obviously I didn't know what I was doing.

Let's say my data model is defined as:

public class Book
{
    public int Id { get; set; } = 0;
    [Required]
    [MaxLength(75)]
    [Display(Name = "Book Title")]
    public string Title { get; set; }
    [Required]
    [MaxLength(50)]
    public string Author { get; set; }
    [Required]
    [Range(0,99)]
    public decimal Price { get; set; }
    [Required]
    [Range(0, 5)]
    public int Rank { get; set; }
}

I found that if is use:

@Html.EditorFor(model => model.Book)

...on my .cshtml (edit or create) page, I can get a basic edit or create screen that respects validation and other attributes for all fields in a model. Great! I could use this for basic admin data editing.

The problem is twofold:

  1. On my Edit page, I need my "Id" field to be read only
  2. On my Create page, I need my "Id" field to default to 0 and be read only

Any combination of:

    //[ScaffoldColumn(false)]
    //[HiddenInput(DisplayValue =false)]
    //[HiddenInput]
    //[DefaultValue(0)]
    //[ReadOnly(true)]
    //[Editable(false)]

...seemingly does not work.

Is there a way to accomplish my two requirements listed above?

I ran into this myself not too long ago. [HiddenInput(DisplayValue =false)] does work but when you scaffold the data model into the page (or view) it still generates the same syntax as the other inputs. However, at runtime, the input is rendered as a hidden input.

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