向用户显示成功消息

时间:2017-01-02 18:46:57

标签: c# html asp.net-mvc message

我正在使用ASP.net核心剃刀引擎。我正在进行注册,并且我想在注册成功时向用户显示成功消息 这是我的代码

我的.cs文件

namespace login.Controllers
{
    public class HomeController : Controller
    {

        private readonly UserFactory userFactory;

        public HomeController(UserFactory user) {
            userFactory = user;
        }

        // GET: /Home/
        [HttpGet]
        [Route("")]
        public IActionResult Index()
        {
            ViewData["message"] = false;
            return View();
        }

        [HttpPost]
        [Route("")]
        public IActionResult Register(Home model)
        {
            if(!ModelState.IsValid)
            {
                return View("Index", model);
            }
            PasswordHasher<Home> Hasher = new PasswordHasher<Home>();
            model.Password = Hasher.HashPassword(model, model.Password);
            userFactory.Add(model);
            ViewData["message"] = true;
            return RedirectToAction("Index");
        }
    }
} 

我的html文件

@model login.Models.Home

@using(Html.BeginForm("Register","Home"))
{
    <h1>Please Register</h1>
    <p>
       <label>Your First Name</label>
        @Html.TextBoxFor(s=>s.FirstName)
        @Html.ValidationMessageFor(s => s.FirstName)
    </p>
    <p>
        <label>Your Last Name</label>
        @Html.TextBoxFor(s=>s.LastName)
        @Html.ValidationMessageFor(s => s.LastName)
    </p>
     <p>
        <label>Your Email</label>
        @Html.TextBoxFor(s=>s.Email)
        @Html.ValidationMessageFor(s => s.Email)
    </p>
    <p>
        <label>Your Password</label>
        @Html.TextBoxFor(s=>s.Password)
        @Html.ValidationMessageFor(s => s.Password)
    </p>
    <p>
        <label>Confrim Password</label>
        @Html.TextBoxFor(s=>s.PasswordConfirmation)
        @Html.ValidationMessageFor(s => s.PasswordConfirmation)
    </p>
    <input type="submit" name="submit" value="Register!"/>
}
 @if(ViewData["message"] == "true")
      {
          <p>Success</p>
      }

我也改为TempData [“message”] ==“false”,所以看看我的html中是否会收到任何消息。但该消息不会在我的HTML中呈现

3 个答案:

答案 0 :(得分:2)

您的代码存在两个问题。

首先,在您使用ViewData的控制器中,在使用TempData的视图中 - 它们是不同的容器。始终如一地使用其中一个。

您还需要注意ViewData仅在请求期间存在,因此当您进行重定向时,它会消失 - 看起来更合适的是TempData

其次,您始终在ViewData["message"]操作中将false设置为Index,并在注册后重定向到Index,即使您要检查在您的视图中,相同的容器将产生错误,并且消息不会显示。只有在视图中渲染后才需要将值设置为false。

答案 1 :(得分:2)

你可以实用这段代码:

代码cs。

\> let pr = (0 :. 0, 3 :. 5) in index pr <$> range pr
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]  -- [0..17] 

代码剃须刀

\> import Data.Array (array, (!))
\> let f i j = (i :. j, "row: " ++ show i ++ ", col: " ++ show j)
\> let a = array ((0 :. 0), (3 :. 3)) [f i j | i <- [0..3], j <- [i..3]]
\> a ! (2 :. 3)
"row: 2, col: 3"

答案 2 :(得分:0)

在控制器中,您设置了ViewData,然后在视图中查看TempData。更新此项以匹配,您的代码应该可以正常工作。

相关问题