【问题标题】:To pass value in DropDrownList to the Controller using ajax使用 ajax 将下拉列表中的值传递给控制器
【发布时间】:2016-04-27 10:26:57
【问题描述】:

我有两个文本框和一个下拉列表。我已经通过 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 )
    {     
    ....   
    }
}

【问题讨论】:

  • 您似乎还没有将其绑定到模型。使用 DropDownListFor 并将其绑定到模型。您选择的值将在您的模型中可用。

标签: c# asp.net ajax asp.net-mvc asp.net-mvc-4


【解决方案1】:

根据您的示例,参数应为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 的 cmets,我更新了模型以包含选项列表。

【讨论】:

  • 这不起作用 - 您需要另一个属性(例如)IEnumerable&lt;SelectList&gt; CusList 用于选项(然后是 @Html.DropDownListFor(m =&gt; m.CusName, Model.CusList, ....)
  • @StephenMuecke 非常正确,谢谢。我也会向视图模型添加一个选定的值和选项。有机会我会更新答案。
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2013-11-11
  • 1970-01-01
  • 2014-05-24
相关资源
最近更新 更多