【问题标题】:Upload Image through jquery Ajax into Model Data into Controller MVC/Razor通过 jquery Ajax 上传图片到 Model Data 到 Controller MVC/Razor
【发布时间】:2019-10-20 04:29:56
【问题描述】:

View 有通过 Ajax/jquery 传递给控制器​​的数据。它不是一种形式。 Ajax 调用是在 Click 函数上进行的

剃刀视图

<div class="form-group">
 @Html.LabelFor(model => model.AddAUser.UserAgeMonths, htmlAttributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
   @Html.EditorFor(model => model.AddAUser.UserAgeMonths, new { htmlAttributes = new { @id = "UserAgeMonths", @class = "form-control" } })
</div>
</div>

 <div class="form-group">
    <div class="col-md-10">
       <input type="file" name="AddAUser.UserImageFile" class="form-control-file" id = "UserProfileImage" />
    </div>
</div>

型号

[Column("intAgeMonths")]
[DisplayName("User's Age in Months")]
public Int16 UserAgeMonths { get; set; }

[NotMapped]
[DisplayName("Upload your profile picture")]
public HttpPostedFileBase UserImageFile { get; set; }

控制器

 [HttpPost]
public IHttpActionResult AddUser([FromBody]Customer user)
{
}

Ajax Jquery 调用

  $('#AddButton').on("click", function (e) {
        e.preventDefault();       
        var UserMonthsParam = $('#UserAgeMonths').val();
        var userParam = $('#LoggedInUser').val();
        var UserImageParam = $('#UserProfileImage').get(0).files;
        var button = $(this);
        $.ajax({
            //Url should contain the method you want to run
            url: "/api/customer/AddUser",
            //Method will be one of the REST API verb
            method: "POST",
            //These are all the parameters to be passed to method for rest api
            data: {               
                AgeMonths: UserMonthsParam,
                UserImageFile : UserImageParam[0]
            },
            dataType: 'json',
            success: function (data) {
                alert("User has been added successfully");
            },
            error: function () {
                alert("Error occured!!")
            }
        });

    });

但是在将图像数据传递给控制器​​时出现错误。它说非法调用。我不确定如何将图像数据传递给控制器​​中的模型数据。

【问题讨论】:

    标签: jquery asp.net ajax asp.net-mvc razor


    【解决方案1】:

    这是我用来上传图片并保存的。

    在下面的示例中,我在视图中使用了一个拖放区,但您可以使用任何您需要的内容并以与下面示例相同的方式保存数据。

    
    View 
    
    <div class="details-form-container">
        <h3>Upload Photos</h3>
        <div class="spacer_0"></div>
        <div class="dropzone dz-form">
            <div class="dz-message needsclick">
                <p class="txt">
                    Drop files here or click to upload.<br />
                    <span>Valid extensions: <b>jpg, gif, png</b> | Max filesize: <b>4MB</b></span>
                </p>
            </div>
        </div>
        <div class="spacer_1"></div>
    </div>
    
    
    <script>
    
        $(".dz-form").dropzone({
        url: "@Url.Action("upload")",                            
        queuecomplete: function (file, response) {
        showAlert('alert', 'success', 'Photos', 'Upload complete.');
        setTimeout(function () {
            window.location.href = '@Url.Action("edit/" + @Model.AgentID  + "/photos")';
        }, 1000);
        }
    
    </script>
    
    
    Controller
    
            [HttpPost]
            public ActionResult Upload()
            {
                bool isValid = false;
    
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    if (file == null)
                    {
                        isValid = false;
                    }
                    if (file.ContentLength > 4 * 1024 * 1024)
                    {
                        isValid = false;
                    }
                    if (!UploadImage.IsFileTypeValid(file))
                    {
                        isValid = false;
                    }
                    isValid = true;
    
                    if (isValid)
                    {
                        // code to save the photo                    
                    }
                }
    
                if (isValid == false)
                {
                    return Json(new { Message = "Error" });
                }
                else
                {
                    return Json(new { Message = "Success" });
                }
            }
    
    

    【讨论】:

    • 需要 dropzone.js?
    • @pcalkins 是的,确实如此
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 2020-01-26
    相关资源
    最近更新 更多