【发布时间】:2017-07-05 22:44:34
【问题描述】:
我想在我的视图中使用元数据,但我的模型(ToDoTable)包含在视图模型(ModelsViewList)中,我不知道如何访问模型。@foreach(ViewData.ModelMetadata.Properties 中的 var 属性)不起作用:(。
型号:
public partial class ToDoTable
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[Required(ErrorMessage = "Please write name of event.")]
public string EventName { get; set; }
[MaxLength(50, ErrorMessage = "Description must be shorter than 50 characters ")]
[Required(ErrorMessage = "Proszę podać opis.")]
public string Description { get; set; }
[Display(Name = "Tu wpisz format daty")]
[DataType(DataType.Date, ErrorMessage = "Date mast be in format described")]
public string Data { get; set; }
}
控制器:
using System.Web.Mvc;
using ToDoLibrary.Abstract;
using ToDoUI.ModelsViews;
namespace ToDoUI.Controllers
{
public class HomeController : Controller
{
IToDoRepository repository;
public HomeController(IToDoRepository rep)
{
repository = rep;
}
public ViewResult List()
{
ToDoLibrary.ToDoTable model = new ToDoLibrary.ToDoTable();
ModelsViewList modelView = new ModelsViewList()
{
FromRepository = repository.FromRepository,
ModelDB = model
};
return View(modelView);
}
}`
}
查看:
@model ToDoUI.ModelsViews.ModelsViewList
@{
ViewBag.Title = "List";
}
<div class="row">
<div class="col-lg-6 main tile1 col-lg-push-6">
pierwsza kolumna
@using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="panel-body">
@foreach (var property in ViewData.ModelMetadata.Properties)
{
switch (property.PropertyName)
{
case "ID":
break;
default:
<div class="form-group">
<label>@(property.DisplayName ?? property.PropertyName)</label>
@if (property.PropertyName == "Description")
{
@Html.TextArea(property.PropertyName, null, new { @class = "form-control", rows = 5 })
}
else
{
@Html.TextBox(property.PropertyName, null, new { @class = "form-control" })
}
@Html.ValidationMessage(property.PropertyName)
</div>
break;
}
}
</div>
<div class="panel-footer">
<input type="submit" value="Zapisz" class="btn btn-primary" />
@Html.ActionLink("Anuluj i wróć do listy", "Index", null, new
{
@class = "btn btn-default"
})
</div>
}
</div>
</div>
【问题讨论】:
标签: c# asp.net-mvc