2015-12-17 43 views
2

我試試這個代碼: -ASP.NET MVC重定向到操作不會呈現最終查看

如果沒有查詢字符串提供給索引方法,然後呈現分支定位器視圖。在該視圖中選擇分支標識後,請回發到重定向路徑結果或操作結果方法,然後使用所選分支標識的查詢字符串重定向回索引。

我可以在沒有查詢字符串的情況下成功運行代碼。 我什至運行索引視圖,可以看到模型正常工作,但索引視圖不呈現,分支選擇器視圖仍然存在。在執行重定向時,網絡開發人員工具會正確顯示正確的URL和查詢字符串。

(注意:兩種方法都在同一個控制器上)。

如果我直接在瀏覽器地址欄中添加相同的查詢字符串,它工作正常!

我有這樣的代碼:

[HttpGet] 
public ActionResult Index() 
{ 
    var querystringbranchId = Request.QueryString["branchId"]; 

    if(!string.IsNullOrEmpty(querystringId)) 
    { 
     ....do stuff like build a model using the branchId... 

     return View(Model); 
    } 

    return View("BranchSelector") 
} 

[HttpPost] 
public RedirectToRouteResult BranchDetails(FormCollection formCollection) 
{ 
    var querystringBranchId = formCollection["BranchList"]; 
    var branchId = int.Parse(querystringBranchId); 

    return RedirectToAction("Index", new { branchId }); 
} 
+0

你能分享你的索引視圖代碼嗎? – Dilip

+0

索引代碼僅將Querystring解析爲INT,然後使用返回模型的服務。謝謝! – AlwaysLearning

+2

AlwaysLearning:這與經典ASP無關,請重新提出您的問題。 – Paul

回答

2

嘗試在帖子上使用強類型模型,並將param指定爲實際參數 - 使用View模型對您來說會更好。

我已經測試過下面的 - 它似乎按預期工作對我來說:

[HttpGet] 
public ActionResult Index(int? branchId) 
{ 
    if (branchId.HasValue) 
    { 
     return View(branchId); 
    } 

    return View("BranchSelector"); 
} 

[HttpPost] 
public RedirectToRouteResult BranchDetails(MyModel myModel) 
{ 
    return RedirectToAction("Index", new { myModel.BranchId }); 
} 

public class MyModel 
{ 
    public int BranchId { get; set; } 
} 

的觀點:

<div> 
    @using (Html.BeginForm("BranchDetails", "Home", FormMethod.Post)) 
    { 
     @Html.TextBox("BranchId","123") 
     <input type="submit" value="Go"/> 
    } 
</div> 
-1

這會爲你工作。乾杯:D

return RedirectToAction(「Index」,「ControllerName」,new {branchId = branchId});

+0

最初試過這個,如果變量名和查詢字符串一樣,不需要,謝謝! – AlwaysLearning

1

@MichaelLake感謝您的文章我發現這個問題。我試過你的代碼,果然它按預期工作。我沒有提到我正在使用裝有分支的Kendo組合框控件(!)。我沒有提到,因爲我需要的實際數據在post方法中是可用的,所以認爲問題出在Controller方法上。我將Kendo的控制名稱作爲BranchList,將其更改爲BranchId,現在可以按照預期的方式使用原始代碼!劍道名稱成爲元素ID,並且必須匹配才能工作。

非常感謝!

相關問題