表单提交成功后如何显示成功消息

时间:2019-01-27 07:59:38

标签: c# asp.net-mvc

我正在学习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,因此希望能获得任何帮助。

1 个答案:

答案 0 :(得分: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>
  }
}

希望它会对您有所帮助。

相关问题