ASP.Net MVC3 Dropdownlist and passing data

2019-07-17 02:25发布

问题:

I have this Controller

    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();
    }

And the corresponding 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)
}

I am trying to figure out how to pass the selected PartnerID from the view back to the controller. Any pointers would be appreciated. I have looked at other posts but cannot seem to locate a solution that will help with this.

Thanks in advance for your time.

回答1:

You can create an ActionResult accepting a FormCollection parameter in order to get the values from the controls in you view like this:

In the View to Populate the List:

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

In the Server side to get the value:

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