How to catch postpack result to Web Api

68 views Asked by At

I know I have done some basic mistake, but I can't find solution by myself, I have next form at ASP MVC 4

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "frmMy", data_bind = "submit: onSubmit", action = "/api/MyService/SaveUpload", enctype = "multipart/form-data" }))
    {
 <button type="submit" class="btn btn-default">Save</button>
}

and web api method

       [HttpPost]
        [AllowAnonymous]       
        public async Task<HttpResponseMessage> SaveUpload()
        {

            // Check if the request contains multipart/form-data. 
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/");

            var provider = new MultipartFormDataStreamProvider(root);

            try
            {              
                await Request.Content.ReadAsMultipartAsync(provider);  
...
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

but after /api/MyService/SaveUpload call my page is make redirect to web api method. How to prevent this behavior and catch method result on page.

1

There are 1 answers

0
shwetaOnStack On

This is happening because you are not telling the Beginform method what to do when the call is successful or unsuccessful. There are a few things you can do to correct this.

  1. Instead of directly calling the api from view, You can make a call to an action method of MVC controller that will in turn call the api. On a successful return, your action method can decide what you want to do with the view, as in redirect to a different view/action or show some kind of notification.
  2. If you don't want to add another layer, you can use AJAX.BeginForm instead (I am not sure if html.beginform allows success handlers) and then you'll have to write a javascript success/error handler function (a normal js function) and pass that to Ajax.Beginform in ajaxoptions. So that it will execute that handler function based on what your API returns (success /error). In that javascript handler function, you can write script to show a success method to the user or whatever next logical step for your application is. More on Ajax.BeginForm ajax optionshere.