注册页面视图在主页面视图中不起作用

时间:2015-09-17 10:24:34

标签: asp.net-mvc-4

首先,我有一个像这样的注册页面

 @using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

<form role="form" action="" method="post" class="login-form">
    <div class="form-group">
        <div>
            @Html.TextBoxFor(model => model.Name, new { @class = "form-username form-control", placeholder = "Name" })
        </div>
    </div>
    <div class="form-group">
        @Html.TextBoxFor(model => model.UserName, new { @class = "form-username form-control", placeholder = "User Name" })
    </div>
    <div class="form-group">
        @Html.TextBoxFor(model => model.Email, new { @class = "form-username form-control", placeholder = "Email" })
    </div>
    <div class="form-group">
        @Html.PasswordFor(model => model.Password, new { @class = "form-username form-control", placeholder = "Password" })
    </div>
    <input type="submit" value="Register" class="btn" />
</form>

}

当我尝试在该页面注册时,我注册并向数据库添加帐户。但是我想在主页面上使用这个注册页面渲染并使用那样但是当我这样做时它不起作用。< / p>

<div class="form-bottom">                    
     @RenderPage("~/Views/User/Register.cshtml")
 </div>

这是控制器代码。

 public ActionResult Register()
    {
        return View(new RegisterModel());
    }

    [HttpPost]
    public async Task<ActionResult> Register(RegisterModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var siteContext = new SiteContext();
        var user = new User
        {
            Name = model.Name,
            Email = model.Email,
            Password=model.Password,
            UserName=model.UserName
        };

        await siteContext.Users.InsertOneAsync(user);
        return RedirectToAction("Profile", "MainPage");
    }

1 个答案:

答案 0 :(得分:0)

说实话,当你使用Html.BeginForm()时,整个视图有点乱,你不需要另外form。您的观点应如下所示:

@using (Html.BeginForm("{Action}", "{Controller}", FormMethod.Post, new { @class = "login-form"})) 
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        <div>
            @Html.TextBoxFor(model => model.Name, new { @class = "form-username form-control", placeholder = "Name" })
        </div>
    </div>
    <div class="form-group">
        @Html.TextBoxFor(model => model.UserName, new { @class = "form-username form-control", placeholder = "User Name" })
    </div>
    <div class="form-group">
        @Html.TextBoxFor(model => model.Email, new { @class = "form-username form-control", placeholder = "Email" })
    </div>
    <div class="form-group">
        @Html.PasswordFor(model => model.Password, new { @class = "form-username form-control", placeholder = "Password" })
    </div>
    <input type="submit" value="Register" class="btn" />
}

您需要将{Action}替换为操作名称Register。同时将{Controller}替换为控制器的名称。

一些有用的documentation