次のコードを取得しました:
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
}
.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 から 2 番目の [作成] メソッドを入力しましたが、プロパティ値にアクセスできないようです。(新しく作成されたオブジェクトから)
しかし、タイプをオブジェクトから「有効なモデルタイプ」(「車」など)に変更すると、入力した値が表示されます。
[HttpPost]
public ActionResult Create(Car entity)
{
//Can access any propertyvalues, but its not dynamic!
}
そして、私はそれを動的に必要としています..これらのプロパティ値を取得するにはどうすればよいですか? それとも、何らかの形で HTML-Response からそれらを取得しようとする必要がありますか? 最善の方法は何ですか、助けてください..