2013-07-02 37 views
0

我希望我的mvc像我的經典asp示例一樣行事。我的經典asp例子很簡單。 我可以添加與np的列表框一樣多的值。我的mvc只允許我每次添加一個值就替換每個值。我如何讓我的mvc像Classic asp.net一樣工作。MVC文本框列表

Classic Asp.net

aspx。

<asp:textbox runat="server" ID="StoreToAdd" ></asp:textbox> 
<asp:Button ID="btnAddStore" runat="server" Text="Add" OnClick="btnAddStore_Click1" /> 

後端C#

protected void btnAddStore_Click1(object sender, EventArgs e) 
    { 
     lstStores.Items.Add(StoreToAdd.Text); 
     StoreToAdd.Text = ""; 

    } 

MVC視圖

@using(Html.BeginForm("Index", "Home")) { 
@Html.TextBoxFor(mod => mod.StoreToAdd, new { Style = "height:20px; " }) 
<div align="center"> 
    <input type="submit" name="addS" id="addS" value="Add" 
     /></div> 

@Html.ListBoxFor(model => model.lstStores, new  
new MultiSelectList(Model.lstStores), 
    new { style = "width:225px;height:255px" }) 

} 

控制器

[HttpPost] 
    public ActionResult Index(HomeModel model) 
    { 

     model.lstStores = new List<string>(); 
     model.lstStores.Add(model.StoreToAdd); 
     return View(model); 
    } 

回答

0

你在你的控制器這樣做:

model.LstStores = new List<string>(); 

您不希望每次重置您的列表嗎?

也許你可以檢查列表已經被第一次實例化,並且只需添加新的項目,如果它具有:

[HttpPost] 
    public ActionResult Index(HomeModel model) 
    { 
     if (model.lstStores != null) 
     { 
      model.lstStores.Add(model.StoreToAdd); 
     } 
     else 
     { 
      model.lstStores = new List<string>(); 
      model.lstStores.Add(model.StoreToAdd); 
     } 

     return View(model); 
    }