使用 ajax 将 DropDrownList 中的值传递给控制器

本文关键字:值传 控制器 ajax DropDrownList 使用 | 更新日期: 2023-09-27 18:31:13

我有两个文本框和一个下拉列表。我已经通过 Ajax.BeginForm() 方法使用它们的 id 将文本框的值传递给控制器操作方法。但是如何传递下拉列表的值,因为它没有由id定义。这是我的代码:

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 )
    {     
    ....   
    }
}

使用 ajax 将 DropDrownList 中的值传递给控制器

根据您的

示例,该参数应可用作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的评论,我已经更新了模型以包含选项列表。