简体   繁体   中英

Asp.NET MVC 6, TagHelper “asp-for” to Model itself

Lets say I have this partial View:

@model DateTime?
<input asp-for="???" class="form-control" />

What goes to ??? to bind to the Model its self?

使用:

<input asp-for="@Model" class="form-control" />

It looks like asp-for tag helper sets the "name" and the "value" attributes of an input html tag. If your model is a simple type or a complex type that behaves like a value type such as string or DateTime?, asp-for helper fails at setting the "name" attribute. So your options are:

@model DateTime?
<input name="mytime" value="@Model" class="form-control" />

And the controller:

public IActionResult ReadMyForm(DateTime? mytime)
{
    // Do your thing...
    return Ok();
}

Or if you insist on using asp-for, then you can employ a little hack:

@model DateTime?
@{
    var mytime = Model;
}
<input asp-for="@mytime" class="form-control" />

Better late than never, I guess :)

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