ASP.NET MVC 重定向到操作不会呈现最终 View

标签 asp.net asp.net-mvc razor routes

我正在尝试这段代码:-

如果没有向索引方法提供查询字符串,则呈现分支定位器 View 。当在该 View 中选择分支 ID 时,回发到重定向到路由结果或操作结果方法,然后使用所选分支 ID 的查询字符串重定向回索引。

我可以在没有查询字符串的情况下成功运行代码。 我什至运行了索引 View ,可以看到模型正在工作,但是索引 View 不会呈现,分支选择器 View 仍然存在。执行重定向时,网络开发人员工具会显示正确的 URL,并正确放置查询字符串。

(注意:两种方法都在同一 Controller 上)。

如果我直接在浏览器地址栏中添加相同的查询字符串,它就可以正常工作!

我有这个代码:

[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 });
}

最佳答案

尝试在帖子中使用强类型模型,并将参数指定为实际参数 - 使用 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; }
}

View :

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

关于ASP.NET MVC 重定向到操作不会呈现最终 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34330495/

相关文章:

c# - WebAPI Controller 继承和属性路由

c# - ExecuteAsync() 导致硬崩溃,无一异常(exception)

asp.net-mvc - 如何将 BundleConfig.cs 添加到我的项目中?

html - razor div 跳过 css::after

javascript - 从同一页面调用两个按钮不起作用

c# - 从c#中的json字符串中检索数据

asp.net - jquery getJson 未将任何值传递给 Controller

c# - 将文本框值复制到另一个 - ASP.NET MVC Razor

c# - 用 Razor 生成一个 html 表。表中的每一列 = 我的数据源中的 1 行

javascript - Razor 在 javascript 中查看 if/else 语句