【问题标题】:mvc - How to assign a value to a partial view property from withing its parent viewmvc - 如何从其父视图中为部分视图属性分配值
【发布时间】:2017-09-29 21:33:20
【问题描述】:

我有一个视图 A、视图 B 和一个视图 _C。

View _C 是在 View A 和 B 内渲染的局部视图:

查看 A:

<div style="margin-top:20px;">

    <div>
        @Html.Partial("~/Views/_C.cshtml", null, new ViewDataDictionary { { "WithRedirect", "true" } });
    </div>

</div>

查看 B

<div style="margin-top:20px;">

    <div>
        @Html.Partial("~/Views/_C.cshtml", null, new ViewDataDictionary { { "WithRedirect", "false" } });
    </div>

</div>

视图C(部分视图)-代码片段:

.
.

<td style="padding-bottom: 8px;">
   @Html.EditorFor(model => model.CurrentPassword, new { htmlAttributes = new { @class = "form-control k-textbox checkError", placeholder = "Enter current password" } })
</td> 
.
.

渲染局部视图时,我需要设置一个标志“WithRedirect”以便稍后在控制器中引用它来决定是否需要重定向到另一个视图:

string withRedirect = this.ViewData.ContainsKey("WithRedirect") ? this.ViewData["WithRedirect"].ToString() : string.Empty;

if(WithRedirect.Equals("true") return Redirect(returnUrl ?? Url.Action("Index", "Page1")); 别的 return Redirect(returnUrl ?? Url.Action("Index", "Page2"));

调试控制器时,WithRedirect变量为空字符串。

我做错了什么,解决办法是什么?

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-mvc-partialview


    【解决方案1】:

    在您的局部视图 (_C.cshtml) 中,您可以从 ViewDataDictionary 读取值并将其设置为 form 内的输入字段。当您提交表单时,该值也将被提交。您可以在您的 http post 操作方法中有一个参数,该参数将接收此输入字段值,并使用该参数有条件地重定向到 page1 或 page 2。

    @model LoginViewModel
    @using (Html.BeginForm("Login","Home")) 
    {
        <input type="hidden" name="withRedirect" value="@ViewData["WithRedirect"]" />
        @Html.LabelFor(f=>f.Password)
        @Html.TextBoxFor(x=>x.Password )
        <input type="submit" />
    }
    

    现在在您的操作方法中

    [HttpPost]
    public ActionResult Login (LoginViewModel model,bool withRedirect)
    {
       //to do : Do something
       if(withRedirect)
       {
          return RedirectToAction("Index","Page1"); 
       } 
       return RedirectToAction("Index","Page2"); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多