2011-11-21 112 views
1

我有一個簡單的MVC3應用程序,我想從服務中檢索一些配置細節,允許用戶編輯和保存配置。RedirectToAction不按預期工作

如果在保存過程中檢測到任何錯誤,這些錯誤將被退回並報告給用戶。

問題是,包含錯誤的配置無法被調用,並且當前保存的值剛剛重新顯示。

單步執行代碼,當檢測到錯誤時,它應該使用傳遞的配置對象重定向到自身,但它不會,並且使用沒有參數的方法。

任何人都可以看到我要去哪裏錯了嗎?

下面是正在叫兩個控制器方法:

// 
// GET: /Settings/Edit/ 
    public ActionResult Edit() 
{ 
    SettingsViewModel config = null; 

    // Set up a channel factory to use the webHTTPBinding 
    using (WebChannelFactory<IChangeService> serviceChannel = 
     new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl))) 
    { 
     // Retrieve the current configuration from the service for editing 
     IChangeService channel = serviceChannel.CreateChannel(); 
     config = channel.GetSysConfig(); 
    } 

    ViewBag.Message = "Service Configuration"; 

    return View(config); 
} 

// 
// POST: /Settings/Edit/ 
[HttpPost] 
public ActionResult Edit(SettingsViewModel config) 
{ 
    try 
    { 
     if (ModelState.IsValid) 
     { 
      // Set up a channel factory to use the webHTTPBinding 
      using (WebChannelFactory<IChangeService> serviceChannel = new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl))) 
      { 
       IChangeService channel = serviceChannel.CreateChannel(); 
       config = channel.SetSysConfig(config); 

       // Check for any errors returned by the service 
       if (config.ConfigErrors != null && config.ConfigErrors.Count > 0) 
       { 
        // Force the redisplay of the page displaying the errors at the top 
        return RedirectToAction("Edit", config); 
       } 
      } 
     } 

     return RedirectToAction("Index", config); 
    } 
    catch 
    { 
     return View(); 
    } 
} 

回答

2
return RedirectToAction("Index", config); 

重定向時,您無法通過複雜的對象是這樣的。您將需要逐個傳遞查詢字符串參數:

return RedirectToAction("Index", new { 
    Prop1 = config.Prop1, 
    Prop2 = config.Prop2, 
    ... 
}); 

此外,我無法在控制器中看到索引操作。也許這是一個錯字。我注意到的另一件事是你有一個Edit GET動作,你可能試圖重定向,但是這個Edit動作不帶任何參數,所以它看起來很奇怪。如果您嘗試重定向到POST編輯操作,那麼顯然這是不可能的,因爲重定向始終在GET上。

+0

感謝您的幫助(再次; o)。你最近一直在幫助我。有任何其他方式來傳遞複雜的對象嗎?我在SettingsViewModel中有30多個參數。 – TeamWild

+0

@TeamWild,你將它冷藏在一個臨時存儲位置並獲取一個唯一的ID,然後當重定向時將這個唯一ID傳遞給該操作,以便它可以獲取原始對象。 TempData是一種方式,但我個人不喜歡它,因爲它依賴於Session。我可能會將其存儲在我的數據存儲中的臨時文件中。 –

+0

我認爲使用會話ID可以正常工作,因爲如果任何其他會話嘗試使用配置,更改將被丟棄。謝謝。 – TeamWild