[英]Pass Value from View To Controller in Asp.net MVC
我正在尝试将消息传递到另一个视图(实际上是相同的控制器),我可以做到这一点,但是对我来说是个问题。
我是网上新手,似乎不太好..
这是我的C#代码
if (createStatus == MembershipCreateStatus.Success)
{
string registrationMessage = "You have registered successfully";
return RedirectToAction("KurumsalGiris", new { message = registrationMessage });
}
[AllowAnonymous] //sonradan eklendi
public ActionResult KurumsalGiris(string message="")
{
if (User.Identity.IsAuthenticated)
return Content("Zaten giriş yapmışsınız");
ViewBag.RegistrationMessage = message;
return View();
}
和这里的HTML边
@model E_Cv.Models.LogOnModel
@{
ViewBag.Title = "Kurumsal Giriş";
}
<h2>Kurumsal Giriş</h2>
<h2>@ViewBag.RegistrationMessage</h2>
<p>
Please enter your user name and password.
@Html.ActionLink("Yeni Kurum Kaydı", "KurumsalKayit")
if you don't have an account.
</p>
所以我不知道如何通过不同的方式将值传递给另一个视图。.我不想在地址栏上显示这种消息,而用户必须对其进行更改。
其次,我可以使用“获取”方法吗?
您为什么不只返回其他视图而不是重定向? 实际上,首先发布的代码应该被发布到控制器,该控制器返回用于成功登录的视图。
实际上,为什么要重定向到询问用户是否刚刚登录的页面?
其他可能的选项包括对URL中的字符串进行加密,或者仅在URL中传递一个标记,控制器会将其转换为相应的字符串。
您要做的是代替直接返回View而不是返回RedirectToAction :(第二个参数是一个模型,您可以在其中使用相同的模型类E_Cv.Models.LogOnModel为其添加RegistrationMessage属性)
return View("<name of the view>",
new E_Cv.Models.LogOnModel {
RegistrationMessage = "You have registered successfully"
});
或像完成操作一样将数据保存在ViewBag中:
ViewBag.RegistrationMessage = "You have registered successfully";
return View("<name of the view>");
关于最后一个问题,给出消息显示在您的URL中,您使用的是GET方法,如果您返回View而不是重定向,它将避免在URL中显示任何内容
您应该在这种情况下使用TempData
if (createStatus == MembershipCreateStatus.Success)
{
TempData["Message"] = "You have registered successfully";
return RedirectToAction("KurumsalGiris");
}
然后在您看来
@if (TempData["Message"] != null)
{
<h2>@TempData["Message"]</h2>
}
或者,如果您想在控制器中执行此操作,只需保持当前视图不变,然后在控制器中设置ViewBag.RegistrationMessage
ViewBag.RegistrationMessage = TempData["Message"];
如果问题是如何在不使用查询字符串的情况下在控制器之间传递数据,则一个选择是Session对象。
if (createStatus == MembershipCreateStatus.Success)
{
Session["Message"] = "You have registered successfully";
return RedirectToAction("KurumsalGiris");
}
[AllowAnonymous] //sonradan eklendi
public ActionResult KurumsalGiris(string message="")
{
if (User.Identity.IsAuthenticated)
return Content("Zaten giriş yapmışsınız");
ViewBag.RegistrationMessage = (string) Session["Message"];
return View();
}
但是,我在下面同意@Jonathan Wood的观点,这不一定是解决您要解决的特定问题的最佳方法。 不过,作为一种通用技术,还是值得了解的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.