0

View has data which is being passed to a controller through Ajax/jquery. It is not a form. Ajax call is made on Click function

Razor View

<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>

Model

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

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

Controller

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

Ajax Jquery Call

  $('#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!!")
            }
        });

    });

But I get an error while passing the image data to the controller. It says Illegal Invocation. I am not sure how to pass Image data to the Model data in the controller.

0

1 Answer 1

1

This is what I use to upload images and save them.

In the below example I use a drop zone in the view but you can use whatever you need and save the data in the same way as the example below.


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

Sign up to request clarification or add additional context in comments.

2 Comments

requires dropzone.js?
@pcalkins yes, it does

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.