【问题标题】:ASP.Net MVC3 Dropdownlist and passing dataASP.Net MVC3 下拉列表和传递数据
【发布时间】:2011-07-26 16:19:45
【问题描述】:

我有这个控制器

    public ActionResult Index()
    {        
        IList<Partner> p = r.ListPartners();            
        ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name");
        return View();
    }

    //
    // POST: /Epub/
    [HttpPost]
    public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload)
    {            
        IList<Partner> p = r.ListPartners();
        ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name");          
        int count = 0;
        for (int i = 0; i < fileUpload.Count(); i++)
        {
            if (fileUpload.ElementAt(i) != null)
            {
                count++;
                var file = fileUpload.ElementAt(i);
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    // need to modify this for saving the files to the server
                    var path = Path.Combine(Server.MapPath("/App_Data/uploads"), Guid.NewGuid() + "-" + fileName);
                    file.SaveAs(path);
                }
            }
        }
        if (count == 0)
        {
            ModelState.AddModelError("", "You must upload at least one file!");
        }
        return View();
    }

以及对应的视图

        @{
    ViewBag.Title = "Index";
}

<h2>You are in the epub portal!</h2>
@Html.Partial("_Download")


@model IEnumerable<EpubsLibrary.Models.Partner>
@{            
    @Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners)
}

我试图弄清楚如何将选定的 PartnerID 从视图传递回控制器。任何指针将不胜感激。我查看了其他帖子,但似乎找不到可以帮助解决此问题的解决方案。

提前感谢您的宝贵时间。

【问题讨论】:

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


    【解决方案1】:

    您可以创建一个接受 FormCollection 参数的 ActionResult,以便从您视图中的控件中获取值,如下所示:

    在视图中填充列表:

    <% using (Html.BeginForm("MyActionButton", "Home")) { %>
       <%= Html.DropDownList("MyList",(SelectList)ViewData["testItems"], "None") %>
       <input type="submit" value="send" />
    <% } %>
    

    在Server端获取值:

    public ActionResult MyActionButton(FormCollection collection)
    {
        string value = collection["MyList"];
        return View();
    }
    

    【讨论】:

    • 这与使用 ViewBag 存储值有何不同?当我发布表单时,我需要获取从下拉列表中选择的项目的值并在发布时重新选择它,这样用户就不必这样做了。
    • 嗯,ViewBag 对象用于将值从 Controller 传递给 View。我之前写的是如何将值从视图传递到控制器,这就是你在帖子中提出的问题。您可以做的是使用 ViewBag 将值传递给视图,然后当用户发布视图时,使用上述技术获取该值,然后当您需要再次显示视图时,再次使用 ViewBag 传递选定的值并在 DropDownList 中选择适当的项目。这有意义吗?
    • 非常感谢您的帮助我已经解决了这个问题并感谢您的意见。如果我有代表,我会支持你。
    • 没问题,我们都在这里帮助不被投票嘿嘿;)我很高兴提供帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2011-07-31
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多