2016-07-03 52 views
1

我想爲我的模型對象創建一個創建頁面。我試圖創造的對象具有「一對多」的關係。所以現在我試圖爲它添加多個字段。我已經找到了這個答案: MVC "create view" when there is one to many relationship in model 問題是,我應該至少有10個額外的領域。或者在最好的情況下,我應該有可能手動設置他們的金額。所以我決定使用一個數組。但在C#中,我無法在模型中設置它的大小,因爲數組是動態的。我應該在哪裏設置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> 
} 

回答

1

可以使用ComponentOfOrder的列表。

List<ComponentOfOrder> mymodel=new List<ComponentOfOrder>(); 

,並通過這種方式使用:

mymodel[0].NameOfComponentOfOrder 

這是烏拉圭回合的問題呢?

相關問題