如何在CSHTML中将数据从viewbag传递给模型

时间:2011-03-08 03:14:01

标签: asp.net-mvc-3

我很难使用viewbag将数据传递给我的模型。

以下是一些启发你的例子:

@model UCPBEscheatment.Models.aspnet_Membership
@{
    ViewBag.Title = "AnswerForgotPassword";
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
<em style="font-size:small">@Html.ValidationSummary(true, "Forgot Password was unsuccessful. Please correct the errors and try again.")</em>
<fieldset style="background-color:#f0f0f0">
<legend> Forgot Password </legend>
<br />
 • Second step: <em style="color:Teal"> Answer your secret question</em>
 <br /><br />
<b> Secret Question:</b> @ViewBag.question 
<br /><br />
<b> Secret Answer: </b>@Html.EditorFor(a => a.PasswordAnswer)
<br /><br />        
@{

      INPUT CODE HERE TO PASS A VALUE TO THE MODEL USING VIEWBAG LIKE:

  ex.
      @MODEL.USERID = VIEWBAG.USERID

}
<input type="submit" value="Submit" />


</fieldset>


}

1 个答案:

答案 0 :(得分:2)

它不起作用。您无法分配到帖子中返回的模型。我建议将用户的id添加到表单URL并使用url上的id来查找需要验证密码密码的用户。

@using (Html.BeginForm("validatepassword","account",new { id = ViewBag.UserID }))
{
     ...
}

或者更好的是,在模型上设置用户ID并从那里使用它而不是ViewBag,但仍然在url中使用它来回发。