我正在开发Razor视图组件,我使用下面的代码来定义视图组件。
视图:
@using MyLibrary.Models
@model InputComponentModel
<label asp-for=@Model.model class="control-label"></label>
<input asp-for="@Model.model class="form-control" type=@Model.Type />
<span asp-validation-for=@Model.model class="text-danger"></span>
组件:
public class TextInput
{
public TextInput(ComponentType type)
{
ComponentType = type
}
private ComponentType ComponentType { get;}
public IViewComponentResult Invoke(string id, ModelExpression for)
{
InputComponentModel model = new()
{
FieldId = id,
Type = ComponentType,
model = for.Model
};
return View(model);
}
}
InputComponentModel:
public class InputComponentModel
{
public ComponentType Type { get; set; }
public string FieldId { get; set; }
public object model { get; set; }
}
然后我在我的视图中使用这个视图组件,如下所示
@model Web.Models.RegisterModel
<vc:text-input id="username" for="username"></vc:text-input>
但是当我运行这段代码时,我得到了"for. model"的空值。我想传递这个registermodelmodel username属性到我的View组件。
谢谢
您可以尝试将@Model.UserName
传递给ViewComponent:
<vc:text-input id="username" username=@Model.UserName></vc:text-input>
ViewComponent:
public class TextInput
{
public TextInput(ComponentType type)
{
ComponentType = type
}
private ComponentType ComponentType { get;}
public IViewComponentResult Invoke(string id, string username)
{
InputComponentModel model = new()
{
FieldId = id,
Type = ComponentType,
model = username
};
return View(model);
}
}