我收到了以下代码:
BusinessObjectController.cs:
public ActionResult Create(string name)
{
var type = viewModel.GetTypeByClassName(name);
return View(Activator.CreateInstance(type));
}
[HttpPost]
public ActionResult Create(object entity)
{
//Can't access propertyvalues
}
Create.cshtml:
@{
ViewBag.Title = "Create";
List<string> attributes = new List<string>();
int propertiesCount = 0;
foreach (var property in Model.GetType().GetProperties())
{
//if (property.Name != "Id")
//{
// attributes.Add(property.Name);
//}
}
propertiesCount = Model.GetType().GetProperties().Length - 1; //-1 wegen Id
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>@Model.GetType().Name</legend>
@for (int i = 0; i < propertiesCount; i++)
{
<div class="editor-label">
@Html.Label(attributes[i])
</div>
<div class="editor-field">
@Html.Editor(attributes[i])
@Html.ValidationMessage(attributes[i])
</div>
}
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
如您所见,我在开始时没有在Create.cshtml中定义任何模型,它可以是任何现有类型(来自模型)。
在Create.cshtml中,我正在创建标签和编辑器(文本框),基于指定类型的属性/属性。一切正常,但在我点击“创建”结束后,我从我的BusinessObjectController输入第二个“创建”方法,我似乎无法访问任何属性值? (来自新创建的对象)
但是,如果我将对象的类型更改为“有效的模型类型” - 例如“Car”,它会显示我输入的值:
[HttpPost]
public ActionResult Create(Car entity)
{
//Can access any propertyvalues, but its not dynamic!
}
我需要动态..我怎样才能获得这些属性值?或者我是否需要尝试以某种方式从HTML响应中获取它们?什么是最好的方式,请帮助..
答案 0 :(得分:2)
尝试使用FormCollection
public ActionResult Create(FormCollection collection)
{
//Can access any propertyvalues, but its not dynamic!
}
然后,您可以使用类似
的内容访问这些值 string s = string.Empty;
foreach (var key in collection.AllKeys) {
s += key + " : " + collection.Get(key) + ", ";
}