Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在局部视图中获取模型特性名称_C#_Asp.net Core_Reflection_Asp.net Core Mvc - Fatal编程技术网

C# 如何在局部视图中获取模型特性名称

C# 如何在局部视图中获取模型特性名称,c#,asp.net-core,reflection,asp.net-core-mvc,C#,Asp.net Core,Reflection,Asp.net Core Mvc,我有一个ASP.NET核心部分视图,它要求(例如)一个人的名字和姓氏。局部视图采用以下视图模型: // MyApp.NamePartialViewModel.cs public class NamePartialViewModel{ public string FirstName { get; set; } public string LastName { get; set; } } 局部视图为其视图模型呈现输入元素,如下所示(显然,我省略了标签和不引人注目的验证内容): 最后,父视图

我有一个ASP.NET核心部分视图,它要求(例如)一个人的名字和姓氏。局部视图采用以下视图模型:

// MyApp.NamePartialViewModel.cs
public class NamePartialViewModel{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}
局部视图为其视图模型呈现输入元素,如下所示(显然,我省略了标签和不引人注目的验证内容):

最后,父视图(由控制器显示)如下所示:

// MyApp.MyViewModel.cs
public class MyViewModel {
  public NamePartialViewModel FirstPersonName { get; set; }
  public NamePartialViewModel SecondPersonName { get; set; }
}
@model MyApp.MyViewModel
<form method="post">
  <partial name="NamePartialView" model="@Model.FirstPersonName" />
  <partial name="NamePartialView" model="@Model.SecondPersonName" />
</form>
<input name="FirstPersonName.FirstName" id="FirstPersonName_FirstName" />
<input name="FirstPersonName.LastName" id="FirstPersonName_LastName" />

因此,我需要一些代码,这些代码可以基于父视图模型中属性的名称来构造前缀,父视图模型将成为局部视图的视图模型。

使用
partial
标记辅助对象当您使用
for
传递模型时,可以通过局部视图中的属性名称进行访问

只要您使用标准的帮助程序,就不需要使用
ViewData.TemplateInfo.HtmlFieldPrefix
,但是作为标记帮助程序的作者或希望使用手动标记渲染的人,您需要关心它

NamePartialView.cshtml

@model MyApp.NamePartialViewModel
如果要创建手动标记,请使用以下前缀:
@ViewData.TemplateInfo.HtmlFieldPrefix
MyViewModel.cshtml

@model MyApp.MyViewModel
<input name="FirstPersonName.FirstName" id="FirstPersonName_FirstName" />
<input name="FirstPersonName.LastName" id="FirstPersonName_LastName" />
@model MyApp.NamePartialViewModel

<label asp-for="FirstName" />
<input asp-for="FirstName" />
<label asp-for="LastName" />
<input asp-for="LastName" />

Just in case of creating manual tags, here is the prefix to use:
@ViewData.TemplateInfo.HtmlFieldPrefix
@model MyApp.MyViewModel

<partial name="NamePartialView" for="FirstPersonName" />
<partial name="NamePartialView" for="SecondPersonName" />