开发者

ASP.NET MVC3 Sending Multiple forms from the same page

开发者 https://www.devze.com 2023-03-23 04:14 出处:网络
There are similar posts out there but they do not seem to represent my situation. Apologies in advance if this is a re-post.

There are similar posts out there but they do not seem to represent my situation. Apologies in advance if this is a re-post.

I have my view as

@FileUpload.GetHtml(initialNumberOfFiles:1,allowMoreFilesToBeAdded:true,includeFormTag:true, uploadText: "Upload" )

@model IEnumerable<EpubsLibrary.Models.Partner>
@{ using (Html.BeginForm("Index","Epub")) 
   {
        @Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
        <input type="submit" value="send" id="pickPartner" hidden="hidden"/>
   }        
}

<script type="text/javascript">
    $(".file-upload-buttons input").click(function () {
        $("#pickPartner").click();
    });
</script>

my controller is

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, FormCollection collection)
{
    int selectedPartner, count =0;
    //int selectedPartner = int.Parse(collection["PartnerID"]);
    if(!int.TryParse(collection["PartnerID"], out selectedPartner))
    {
        selectedPartner = 0;
        ModelState.AddModelError("", "You must pick a publishing agency");
    }
    IList<Partner> p = r.ListPartners();
    ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name", selectedPartner);

    //make sure files were selected for upload 
    if (fileUpload != null)
    {
        for (int i = 0; i < fileUpload.Count(); i++)
        {
            //make sure every file selected != null
            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();
}

I am using the file upload helper from Microsoft Web Helpers to upload files. The problem I am having is the helper created a form and I have another form I need to submit data from as well on the same page.

I thought I could link the submit buttons so that when you click upload it also sent the other form data but the data is not being sent. Each form works independently of the other with no issue but I need them to work together. Any advice would be appreciated.

Ok I updated the view with

@model IEnumerable<EpubsLibrary.Models.Partner>
@{ using (Html.BeginForm("Index","Epub")) 
   {
        @Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
        @FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, uploadText: "Upload")
        <input type="submit" value="send" id="pickPartner"/>
   }        
}

But now the file data does not seem to be getting passed anymore.

-- Update --

I have made the following changes. The view now looks like

@model IEnumerable<EpubsLibrary.Models.Partner>
@{ using (Html.BeginForm("Index", "Epub", new { enctype = "multipart/form-data" }))
   {
        @Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
        @FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, uploadText: "Upload")
        <input type="submit" value="send" id="pickPartner"/>
   }        
}

and the controller

[HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, int PartnerID = 0)
        //public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, FormCollection collection)
        {
            int count =0;
            IList<Partner> p = r.ListPartners();
            ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name", PartnerID);
            //make sure files were selected for upload 
            if (fileUpload != null)
            {
                for (int i = 0; i < fileUpload.Count(); i++)
                {
                    //make sure every file selected != null
                    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();
        }
    }

I am trying to figure out how the file data is getting sent over in the post (if it is) so I can save the files.

-- Final Update with Answer --

Well the problem turned out to be two fold.. 1st the issue with @FileUpload and needing to set includeFormTag: false

The other problem I discovered was I needed to make sure in my @Html.BeginForm I included FormMethod.Post This was discovered when the fileUpload count kept coming back as 0. I ran the profiler on firebug and it pointed out that the file data was not actually getting posted. Here is the corrected code below.

my view

@model IEnumerable<EpubsLibrary.Models.Partner>
@{ using (Html.BeginForm("Index", "Epub", FormMethod.Post, new { enctype = "multipart/form-data" }))
   {
        @Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
        @FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, uploadText: "Upload")
        <input type="submit" value="send" id="pickPartner"/>
   }        
} 

my controller

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, int PartnerID = 0)        
{
    int count =0;
    IList<Partner> p = r.ListPartners();
    ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name", PartnerID);
    //make sure files were selected for upload 
    if (fileUpload != null)
    {
        for (int i = 0; i < fileUpload.Count(); i++)
        {
            //make sure every file selected != null
            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();
}

Thank you @Jay and @Vasile Bujac for your help with this.


Set IncludeFormTag to false and put it inside your other form using.

@model IEnumerable<EpubsLibrary.Models.Partner>
@{ using (Html.BeginForm("Index","Epub")) 
   {
        @FileUpload.GetHtml(initialNumberOfFiles:1,allowMoreFilesToBeAdded:true,includeFormTag:false, uploadText: "Upload" )

        @Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
        <input type="submit" value="send" id="pickPartner" hidden="hidden"/>
   }        
}

Update: Try changing the signature of your view to this:

public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, int PartnerID = 0)

Check the overloads for FileUpload.GetHtml and see if there is a parameter to set the field name for your file uploads. Previously it was just the files being uploaded, now its files and a parameter, so naming becomes more important.


You should use the same form for dropdownlist and file inputs. You can do this by putting the FileUpload helper inside the form, and setting "includeFormTag" parameter to false.

@model IEnumerable<EpubsLibrary.Models.Partner>
@using (Html.BeginForm("Index","Epub")) {
        @FileUpload.GetHtml(initialNumberOfFiles:1,allowMoreFilesToBeAdded:true,includeFormTag:false, uploadText: "Upload" )
        @Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
        <input type="submit" value="send" id="pickPartner" hidden="hidden"/>
   }        
0

精彩评论

暂无评论...
验证码 换一张
取 消