【问题标题】:How to show success message after the form submit is successful表单提交成功后如何显示成功信息
【发布时间】:2019-01-27 17:29:45
【问题描述】:

我正在学习 ASP.NET MVC。表单提交后,我想在主视图的提交按钮下显示一条带有部分视图的成功消息。

<form action="myactionLInk" method="post">
     <input type="text" name="Name" placeholder="Enter name here..."/>
     <input type="submit" value="Submit" />
</form>

// Here would be some code to load partialview
<div>
   @Html.Partial("_userpartial")
</div>

这是我的UserContoller

[HttpPost]
public ActionResult userData(FormCollection collection)
{
    //Save name, email and contact to ViewBag
    return PartialView("_userPartial")
}

这里是_userPartial.cshtml

<p> Data of @Viewbag.Name successfully saved.</p>

我希望在成功创建时在提交按钮下加载部分视图。我仍在学习 MVC,因此不胜感激。

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    为什么需要局部视图来显示此成功消息?您可以简单地执行以下操作:

    正如您所说,您对 ASP.NET MVC 还很陌生,所以我在这里为您提供一个完整的解决方案,说明如何在创建实体后显示成功消息。

    先写一个模型类如下:

    public class User
    {
        [Key]
        public int UserId {get; set;}
    
        [Required]
        public int UserName {get; set;}
    }
    

    然后在User控制器中:

    public class UserController: Controller
    {
        [HttpGet]
        public ActionResult CreateUser()
        {
             return View();
        }
    
        [HttpPost]
        public ActionResult CreateUser(User user)
        {
            if(ModelState.IsValid)
            {
              // save the user here
    
              ViewBag.SuccessMessage = user.UserName + " has been created successfully!"
              ModelState.Clear();
              return View();
            }
            return View(user);
       }
    }
    

    然后在您的CreateUser.cshmtl 视图中:

    @using User
    
    @using (Html.BeginForm("CreateUser", "User", FormMethod.Post))
    {
        @Html.EditorFor(m => m.UserName)
    
       <input type="submit" value="Submit" />
    }
    
    @{
      if(ViewBag.SuccessMessage != null)
      {
         <div>
             @ViewBag.SuccessMessage
         </div>
      }
    }
    

    希望对你有帮助。

    【讨论】:

    • 我正在使用部分视图,因为成功消息包含人名,我可能会在以后添加更多详细信息。
    • 我已经更新了答案。检查这一行ViewBag.SuccessMessage = user.UserName + " has been created successfully!"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多