我想在我的視圖中使用元數據,但我的模型(ToDoTable)打包在viewmodel(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>
是的我知道,但沒有改變@model如何做到這一點ToDoUI.ModelsViews.ModelsViewList – Marek
我不確定你的子對象的元數據是否加載到模型中。所以最好的方法是將TodoTable對象傳遞到一個新的視圖中,在這個視圖中你一定可以訪問你的元數據。但是你可以在做這件事之前嘗試一下「ModelDB.ID」的案例:-) –
我正在處理項目,不幸的是所有事情都必須在一個視圖中。 – Marek