简体   繁体   中英

How to post an object from MVC controller to Web Api controller?

Scenario is my MVC view is returning data to Controller action and from my action requirement is to build an object and pass it to an external Web API. I m getting data in my action and building an object as well. Can you please direct me how I should pass object to external Web API.

Also should it be JSON, object or xml ?

I m giving my controller and Web API code below:

Controller action:

 public ActionResult Submit(FormCollection form)
        {
            Options lead = new Options();            
            lead.Situation = form.GetValue("InsuranceFor").AttemptedValue;
            lead.State = form.GetValue("InsuranceState").AttemptedValue; 

            //Here I want to pass object to Web API


            return RedirectToAction("Parameters");
        }

Web API method:

   public void Post(Lead_Options lead)
        {
            leadOptService.AddListOptions(lead);
        }

I just completed a complex implementation just to satisfy similar requirement. I was assigned to post object from C# MVC Controller to an external RESTful Web API. In the future, the Web API will remain, but the C# MVC may be replaced with NodeJS / Angular application. So what I did was, assign the object to a TempData in a Serialized JSON format, then in the View where the page redirects to, conditionally added AngularJS, and implement AngularJS post to the external WebAPI. In your case, the TempData would look something like this:

    this.TempData["lead"] = new JavaScriptSerializer().Serialize(this.Json(lead, JsonRequestBehavior.AllowGet).Data); 

Then, in the redirected view "Parameters", you could add this angular code:

     @if (this.TempData["lead"] != null)
{
    <script type="text/javascript" src="@Url.Content("~/Contents/Scripts/angular.js")"></script>
    <script type="text/javascript">
        angular
       .module('app', [])
       .controller('controllerName', ['$http', '$scope', 'apiFactory', function ($http, $scope, apiFactory) {
           var leadRecord = '@Html.Raw(this.TempData["lead"])';
           var apiUrl = 'https://xxxxxxxxxxxxxx';

           apiFactory({
               method: 'POST',
               url: apiUrl + '/api/apiControllerName/Post',
               data: '=' + leadRecord,
               headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' }
           }).then(function (result) {
               console.log(result);
           });
        }])
        .factory('apiFactory', function ($http, $q) {
            return function (config) {
                var defered = $q.defer();
                $http(config)
                .success(function (result, status, headers, config) {
                    defered.resolve(result);
                })
                return defered.promise;
            }
        })
    </script>        
}

    <div ng-app="app" class="col-sm-12 sign-in-page">
         <div class="row" ng-controller="controllerName">

          .....  contents of redirected page ....

         </div>
    </div>

Your WebAPI - (Assuming it's C# Web API 2.2 should look something like this:

  [HttpPost]
    public string Post([FromBody]string jsonString)
    {
        try
        {
            IDictionary<string, string> data = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonString);

Assuming your object's values are all strings ....

This implementation may not be ideal but it does its job for sure

Oh, alternatively, you could simply add the angular POST to your original view that contains the form controls. But in my case this was not an option because the View must make a full post, the data from the full post must be processed in the model, then the controller gets some of the data from the models and combine it with session information to make up the object, which then has to be sent to a Web API controller..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM