Upload photo with jQuery Dialog in ASP.NET MVC site

会有一股神秘感。 提交于 2020-01-07 02:01:10

问题


I'm building an ASP.NET MVC 3 application, and I'm trying to use a jQuery Dialog to upload a photo. Here is my code, but the problem is that the HttpPostedFileBase object of my model (witch represent the file to upload) is always null on the server side (HttpPost method).

My controller

public ActionResult AddProductPhoto(int id)
{
    var model = new UploadImageModel {ProductId = id};
    return PartialView("_UploadFile", model);
}

[HttpPost]
public ActionResult AddProductPhoto(UploadImageModel model)
{
    // model.File is always null
    return Json(new { Success = true });
}

The model

public class UploadImageModel
{
    public int ProductId { get; set; }

    [FileExtensions(Extensions = "jpg, jpeg, png")]
    public HttpPostedFileBase File { get; set; }
}

The upload partial view (_UploadFile)

@model DalilCompany.Models.UploadImageModel

@using (Html.BeginForm("AddProductPhoto", "Product", FormMethod.Post,
        new { id = "uploadProductPhotoForm", enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)

    @Html.HiddenFor(m => m.ProductId)

    <div>
        @Html.LabelFor(m => m.File)
        @Html.TextBoxFor(m => m.File, new { type = "file" })
    </div>
}

main view

<span productId ="@Model.ProductId" id="add_product_photo_link">
    Upload photo
</span>
<div id="AddPhotoDlg" title="" style="display: none"></div>

<script type="text/javascript">
    $(function () {
        $("#AddPhotoDlg").dialog({
            autoOpen: false,
            width: 550,
            height: 250,
            modal: true,
            buttons: {
                "Upload": function () {
                    $.post("/Product/AddProductPhoto",
                    $("#uploadProductPhotoForm").serialize(),
                    function () {
                        $("#AddPhotoDlg").dialog("close");
                        alert('upload success');
                    });
                    },
                "Close": function () { $(this).dialog("close"); }
            }
        });
    });

    $("#add_product_photo_link").click(function () {
        var id = $(this).attr("productId");

        $("#AddPhotoDlg").html("")
            .dialog("option", "title", "Ajouter une photo")
            .load("/Product/AddProductPhoto/" + id,
                function () { $("#AddPhotoDlg").dialog("open"); });
    });                                         
</script>

回答1:


$(function(){
$("#JqPostForm").submit(function(e){    
   e.preventDefault();  

    $.post("process_form.php", $("#JqPostForm").serialize(),
    function(data){
        if(data.email_check == 'invalid'){

                $("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
        } else {
            $("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
            }
    }, "json");    
});});

I suggest you should use something like that to trigger form submit action




回答2:


I found this question and answer, and I've decide to change my approch and use HTML5 to solve my problem. Thanks and good luck.

With HTML5 you CAN make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div).




回答3:


You can't upload a file using $.post or Jquery's ajax as far as I know. So

$("#uploadProductPhotoForm").serialize()

doesn't serialize the file input.

What you can do in your submit function is:

get the file input using javascript:

var fileInput = document.getElementById("IdOfYourFileInput");

It will have a files property that contains the file selected files then you can upload it using FormData and XMLHttpRequest

var form = new FormData();
form.append("NameOfTheInput", fileInput.files[0]);
form.append("NameOftheId", id);//this is your productId
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Product/AddProductPhoto/", true):
xhr.send(form);


来源:https://stackoverflow.com/questions/18325117/upload-photo-with-jquery-dialog-in-asp-net-mvc-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!