簡體   English   中英

如何將對象從MVC控制器發布到Web Api控制器?

[英]How to post an object from MVC controller to Web Api controller?

場景是我的MVC視圖正在將數據返回到Controller操作,並且從我的操作要求出發是構建一個對象並將其傳遞給外部Web API。 我在執行操作時要獲取數據並也要構建對象。 您能指導我如何將對象傳遞給外部Web API嗎?

還應該是JSON,object或xml嗎?

我在下面提供我的控制器和Web API代碼:

控制器動作:

 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方法:

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

為了滿足類似的要求,我剛剛完成了一個復雜的實現。 我被分配將對象從C#MVC Controller發布到外部RESTful Web API。 將來,Web API仍將保留,但C#MVC可能會被NodeJS / Angular應用程序取代。 所以我要做的是,以序列化JSON格式將對象分配給TempData,然后在頁面重定向到的視圖中,有條件地添加了AngularJS,並將AngularJS發布實現到外部WebAPI。 在您的情況下,TempData將如下所示:

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

然后,在重定向視圖“參數”中,可以添加以下角度代碼:

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

您的WebAPI-(假設它是C#Web API 2.2,看起來應該像這樣:

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

假設對象的值都是字符串...。

這種實現可能不是理想的,但是可以肯定地做到了

哦,或者,您可以簡單地將角度POST添加到包含表單控件的原始視圖中。 但是在我的情況下,這不是一個選擇,因為View必須發布完整的帖子,必須在模型中處理來自完整帖子的數據,然后控制器從模型中獲取一些數據並將其與會話信息結合起來對象,然后必須將其發送到Web API控制器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM