简体   繁体   中英

C# Get nameof a property with the model extension


EDIT

I just noticed that when I tried to store the value of nameof(Model) it came in as "Model" but when I generated the TextBox the name field comes in as DateVerified.Model from this template. I'm super confused why this is happenning.

型号名称


I'm trying to get the name of a property without the . extension after it in order to do some dynamic binding for my Asp.Net Editor Templates but can't seem to get it to work.

This is my template view,

@model DateTime?

@Html.LabelFor(m => m)
<div class="input-group datepicker form-group">
    <span class="input-group-addon">
        <i class="fa fa-calendar"></i>
    </span>
    @Html.TextBox(nameof(Model), Model.HasValue ? 
Model.Value.ToShortDateString() : "", "{0:MM/dd/yyyy}", new { @class = "form-control" })
</div>

As you can see I have different date properties entering in this template and some can be null which is why I'm checking values instead of just using the @Html.TextBoxFor helper. This works great except the name of the property comes in as instances like,

DateVerified.Model
DateCreated.Model

This won't work for my model binding on postback since my properties are just named DateVerified or DateCreated. How can I get the name of these properties but without the extension?

Nevermind. I was being dumb. I changed this line,

@Html.TextBox(nameof(Model), Model.HasValue ? Model.Value.ToShortDateString() : "", "{0:MM/dd/yyyy}", new { @class = "form-control" })

To this,

@Html.TextBox("", Model.HasValue ? Model.Value.ToShortDateString() : "", "{0:MM/dd/yyyy}", new { @class = "form-control" })

And the names of my date properties came in the way I wanted them to look for my Model Binding.

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