当DropDownList更改时,MVC2 ActionResult不执行

时间:2013-01-31 17:45:08

标签: c# asp.net asp.net-mvc asp.net-mvc-2

我正在学习ASP.NET MVC 2并遇到了一个我似乎无法弄清楚的小问题。

基本上我有一个从Access数据库填充的下拉列表,当用户选择一个值我想调用ActionResult作为参数传递选定的值时,我试图通过使用{{ 1}}

下拉数据已经填满了数据,我可以确认javascript函数触发但是我的ActionResult中的断点仍然没有被击中,我很感激任何建议:

型号:

$.post

控制器:

public class SuppliersModel
{
    public SuppliersModel()
    {
    }

    public SuppliersModel(string id)
    {
    }

    private string id;
    public string ID
    {
        get { return id; }
        set { id = value; }
    }

    public SelectList OurSuppliers
    {
        get 
        {
            List<SelectListItem> suppliers = GetSuppliers();
            var list = new SelectList(suppliers, "Value", "Text");
            return list;
        }
    }

    public IEnumerable<string> UniqueSuppliers{get;set;}

    private List<SelectListItem> GetSuppliers()
    {
        var suppliers = new List<SelectListItem>();
        string conn = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;

        using (var connection = new OleDbConnection(conn))
        {
            connection.Open();
            string commandText = "SELECT [Supplier], [ID] FROM [Suppliers] ORDER BY [Supplier]";
            using (var command = new OleDbCommand(commandText, connection))
            {
                command.CommandType = System.Data.CommandType.Text;
                using (OleDbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string id = reader["ID"].ToString();
                        string supplier = reader["Supplier"].ToString();
                        suppliers.Add(new SelectListItem() { Text = supplier, Value = id });
                    }
                }
            }
            connection.Close();
            return suppliers;
        }
    }
}

查看:

public class SuppliersController : Controller
{
    public ActionResult Suppliers()
    {
        SuppliersModel model = new SuppliersModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult SuppliersById(string id)
    {
        System.Diagnostics.Debugger.Break();
        SuppliersModel model = new SuppliersModel(id);
        return View(model);
    }
}

1 个答案:

答案 0 :(得分:1)

我的javascript函数中存在语法错误,修复了它:

<script type="text/javascript">
    $(function () {
        $('#suppliers').change(function () {
            $.post('<%=Url.Action("SuppliersById", "Suppliers")%>', { id: $(this).val() }, 
            function (result) {
            });
        });
    });
</script>