2016-01-21 70 views
2

我有兩個文本框和一個下拉列表。我已經通過Ajax.BeginForm()方法將文本框的值傳遞給控制器​​操作方法。但是如何傳遞dropdownlist的值,因爲它沒有通過id定義。這裏是我的代碼:使用ajax將DropDrownList中的值傳遞給控制器​​

DeliveryIndex.cshtml:

@using (Ajax.BeginForm("CustomerFilter", "Delivery", new System.Web.Mvc.Ajax.AjaxOptions 
{ 
    InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, 
    HttpMethod = "POST", 
    UpdateTargetId = "deliverylist" 
})) 
{    
<input id="from" name="from" type="text" /> 

<input id="to" name="to" type="text" /> 

@Html.DropDownList("CUS_NAME",null,"--Select Customer--",new { @Style = "WIDTH:169PX" }) 

<input type="submit" value="View" id="BtnSubmit" /> 
} 

控制器:

public class DeliveryController : MasterController 
{ 
    public ActionResult DeliveryIndex() 
    {  
     ViewBag.CUS_NAME = new SelectList(db.CUSTOMER_MASTER.ToList().OrderBy(c => c.CUS_NAME), "CUS_NAME", "CUS_NAME"); 
     return View("DeliveryIndex");  
    } 

    [HttpPost] 
    public ActionResult CustomerFilter(string from, string to, string) 
    {  
    .... 
    } 
} 
+1

看起來好像你還沒有將它綁定到模型上。使用DropDownListFor並將其綁定到模型。您選擇的值將在您的模型中可用。 –

回答

3

基於您的示例中的參數應該作爲CUS_NAME

改變你的行動:

[HttpPost] 
public ActionResult CustomerFilter(string from, string to, string CUS_NAME) 
{  
.... 
} 

將予以通過,不過,我想用一個強類型的視圖模型建議。

作爲一個例子:

視圖模型

public class FooViewModel 
{ 
    public string From { get;set; } 
    public string To { get;set; } 
    // represents the selected value 
    public string CusName { get;set; } 
    public List<Customer> AvailableCustomers { get;set;} 
} 

public class Customer 
{ 
    public int Id { get;set;} 
    public string Name { get;set;} 
} 

行動

[HttpPost] 
public ActionResult CustomerFilter(FooViewModel model) 
{  
.... 
} 

查看

@model FooViewModel 
@using (Ajax.BeginForm("CustomerFilter", "Delivery", new System.Web.Mvc.Ajax.AjaxOptions 
{ 
    InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, 
    HttpMethod = "POST", 
    UpdateTargetId = "deliverylist" 
})) 
{    
    @Html.TextBoxFor(m => m.From) 
    @Html.TextBoxFor(m => m.To) 
    @Html.DropDownListFor(m => m.CusName, new SelectList(model.AvailableCustomers, "Id", "Name"),"--Select Customer--",new { @Style = "WIDTH:169PX" }) 
    <input type="submit" value="View" id="BtnSubmit" /> 
} 

更新 根據Stephen Muecke的評論,我已更新模型以包含選項列表。

+1

這是行不通的 - 你需要另一個屬性(比如說)'IEnumerable CusList'來選擇(然後是它的@@ Html.DropDownListFor(m => m.CusName,Model.CusList,....)' –

+0

@ StephenMuecke非常真實,謝謝,我也爲視圖模型添加了一個選定的值和選項,當我有機會的時候我會更新答案。 – hutchonoid

+0

@StephenMuecke現在更新,謝謝。:) – hutchonoid

相關問題