1
モデルオブジェクトの作成ページを作成しようとしています。私が作成しようとしているオブジェクトには、「1対多数」の関係があります。だから私はそれのために複数のフィールドを追加しようとしています。私はこの答えを見つけました: MVC "create view" when there is one to many relationship in model 問題は少なくとも10の追加フィールドが必要です。あるいは、最良の場合には、手動で金額を設定する必要があります。だから私は配列を使うことに決めました。しかし、C#では配列が動的なので、モデルのサイズを設定できません。Razorのアレイのサイズはどこで設定しますか?
質問: ここでは、Razorが作成するフィールドの数を知るように、配列のサイズを設定できます。ここで
は私のモデルです:ここでは
public class OrderCreateView
{
//Other fields
public ComponentOfOrder[] ComponentOfOrders { get; set; }
}
public class ComponentOfOrder
{
public string NameOfComponentOfOrder { get; set; }
}
は、ページを作成のための私のコントローラのメソッドです:
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "anotherStuff,ComponentOfOrders")] OrderCreateView orderCreateView)
{
if (ModelState.IsValid)
{
Order order = new Order
{
//Another fields
};
db.Orders.Add(order);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(orderCreateView);
}
マイカミソリのページ:
@model Safronov.Models.OrderCreateView
@{
ViewBag.Title = "Create";
//Model.ComponentOfOrders = new Safronov.Models.OrdersDB.ComponentOfOrder[10];
//here it doesn't work with error message "Object reference does not point to an instance of an object"
}
some stuff on page
@foreach (var component in Model.ComponentOfOrders)
{
<div class="form-group">
@Html.LabelFor(x => component.NameOfComponentOfOrder, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(x => component.NameOfComponentOfOrder, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(x => component.NameOfComponentOfOrder, "", new { @class = "text-danger" })
</div>
</div>
}