我不想將字典綁定到視圖。但該模型似乎是空的。 棘手的部分是,我在另一個視圖中使用視圖,我無法弄清楚我的錯誤在哪裏。EditorTemplate中的MVC字典
這裏是我到目前爲止的代碼:
第一種模式:
public class QuantityAndSize
{
private Dictionary<String, int> m_Size;
public decimal Quantity {get;set;}
public Dictionary<string,int> Size
{
get
{
return m_Size;
}
set
{
m_Size = value;
}
}
public int SelectedItem {get;set;}
public QuantityAndSize()
{
Quantity = 0;
m_Size = new Dictionary<string, int>();
SelectedItem = 0;
}
}
第二種模式
public class NewItemDeliveryModel
{
#region - member -
private string m_Subject;
private QuantityAndSize m_ShortfallQuantity;
#endregion
#region - properties
[Display(Name = "Betreff")]
public string Subject
{
get { return m_Subject; }
set { m_Subject = value; }
}
[Display(Name = "Fehlmenge")]
public QuantityAndSize ShortfallQuantity
{
get { return m_ShortfallQuantity; }
set { m_ShortfallQuantity = value; }
}
#endregion
#region - ctor -
public NewItemDeliveryModel()
{
m_ShortfallQuantity = new QuantityAndSize();
}
#endregion
}
這裏我對NewItemDeliveryModel
一個視圖@model Web.Models.NewItemDeliveryModel
@{
ViewBag.Title = "NewItemDelivery";
}
<h2>NewItemDelivery</h2>
@using (Html.BeginForm())
{
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.Subject, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Subject)
@Html.ValidationMessageFor(model => model.Subject)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ShortfallQuantity, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ShortfallQuantity)
@Html.ValidationMessageFor(model => model.ShortfallQuantity)
</div>
</div>
</div>
}
和View的QuantityAndSize
@model Web.Models.Structures.QuantityAndSize
<div class="form-group">
@Html.LabelFor(model => model.Quantity, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Quantity)
@Html.ValidationMessageFor(model => model.Quantity)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Size, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Size, new SelectList(Model.Size,"Key","Value"), "Sizes") //<-- Model.Size says that Model is null but i can't figure out why
@Html.ValidationMessageFor(model => model.Size)
</div>
</div>
的問題是,我無法將字典綁定到Html.DropDownList因爲型號爲NULL。 我是相當新的ASP.Net MVC和問題本身似乎很簡單,但我找不到錯誤的原因。 所以我的問題是爲什麼我的模型等於Null?
BTW控制器是非常小的,但爲了完整起見,這裏談到
public class NewItemDeliveryController : Controller
{
// GET: NewItemDelivery
public ActionResult Index()
{
return View("NewItemDelivery");
}
}
你傳遞什麼看法? – Neel
不,我以爲模型會自動綁定@model Web.Models.Structures.QuantityAndSize – Bongo
@Bongo它會自動綁定。但你應該填寫它。像這樣:'ViewData.Model = new NewItemDeliveryModel();'在你的View()調用之前。你應該在Controller中初始化你的字典。 –