简体   繁体   English

提交表单后在 ASP.NET MVC 中。 它不会重定向到其他页面。 它正在加载相同的页面

[英]In ASP.NET MVC after submitting form. it is not redirecting to other page. its loading same page

1.In ASP.NET MVC after successfully registration, in LogIn when entering fields like username and password and after click on submit button. 1.在ASP.NET MVC中注册成功后,在登录时输入用户名和密码等字段,然后点击提交按钮。 2. its not login & not redirecting to another page but it actually looks like refreshing a page and the username entered data is present after clicking submit btn. 2.它不是登录,也不是重定向到另一个页面,但它实际上看起来像刷新页面,并且在单击提交 btn 后会出现用户名输入的数据。 my controller我的控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApplication6mvc16_12.Models;

namespace WebApplication6mvc16_12.Controllers
{
    public class UserController : Controller
    {
        [HttpGet]
        public ActionResult AddorEdit(int id = 0)//(int id = 0)
        {
            User userModel = new User();
            return View(userModel);
        }
        [HttpPost]
        public ActionResult AddorEdit(User userModel)
        {
            // using (UserRegistrationDatabase1Entities dbModel = new UserRegistrationDatabase1Entities () )
            using (Database1Entitiesmodel2 db = new Database1Entitiesmodel2())
            {
                //System.InvalidOperationException: 'The entity type User is not part of the model for the current context.
                //check the AplicationdbContext to be Assign to Var Model that your create
                db.Users.Add(userModel);
                db.SaveChanges();

            }
            ModelState.Clear();
            ViewBag.SuccessMessage = "Registration Successful";
            return View("AddorEdit", new User());
        }
        /// <summary>
        /// login data is not getting accepted. on the web server. data access is possible but not redirecting to other page
        /// </summary>
        /// <returns></returns>


        [HttpGet]
        public ActionResult Login() //(string UserId)
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(User objUser)
        {
            if (ModelState.IsValid)
            {
               // using (Database1Entitiesmodel2 entitiesmodel2 = new Database1Entitiesmodel2())
               using (Database1Entitiesmodel2 db = new Database1Entitiesmodel2())
                {
                    //  var obj = entitiesmodel2.Users.Where(model => model.UserName.Equals(objUser.UserName) && model.Password.Equals(objUser.Password)).FirstOrDefault();
var var = db.Users.Where(model => model.UserName.Equals(objUser.UserName) && model.Password.Equals(objUser.Password)).FirstOrDefault();
                    if (var != null)
                    {
                        //   Session["UserId"] = var.UserId.ToString();
                        // Session["UserName"] = var.UserName.ToString();
                        return RedirectToAction("UserDashboard", "UserController");
                    }
                }
            }

            return View(objUser);
        }

        public ActionResult UserDashboard()
        {
           // if (Session["UserId"] != null)
            {
                return View();
           /* }
            else
            {
                return RedirectToAction("Login");*/
            }
        }
    }
}

my login我的登录

@model WebApplication6mvc16_12.Models.User

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>


@using (Html.BeginForm("Login","User",FormMethod.Post))//(Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<div class="form-horizontal">

    @*<select class="form-control" id="LoginAuthority" name="LoginAuthority" required title="here">
            <option disabled selected>Select Role</option>
            <option>Admin</option>
            <option>Customer</option>
            <option>Sevice Engineer</option>
        </select>
    *@
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.UserId)

    <div class="form-group">
        @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Login" class="btn btn-default" />
           @* <input type="reset" value="Reset" class="btn btn-default" />*@
        </div>
    </div>

</div>
}

<div>
    @Html.ActionLink("Back to Registration", "AddorEdit")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

my user我的用户


namespace WebApplication6mvc16_12.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    public partial class User
    {
        public int UserId { get; set; }

        [Required ( ErrorMessage ="This field is required")]
        [DisplayName("Full Name")]
        public string UserName { get; set; }

        [Required (ErrorMessage = "This field is required")]
        [DisplayName("Email Address")]
        public string Email { get; set; }

        [Required (ErrorMessage =" This field is required")]

        [DataType(DataType.Password)]
        public string Password { get; set; }        

        [Required (ErrorMessage =" This field is required")]
        [DisplayName("Confirm Password")]
        [DataType(DataType.Password)]
        [Compare("Password")]
        public string ConfirmPassword { get; set; }

    }
}

userdashboard用户仪表板

@{
    ViewBag.Title = "UserDashboard";
}

    <fieldset>
        <legend>
            Dashboard Contents
        </legend>

    @*    @if (Session["UserName"] != null)
        {
            < text >
            Welcome @Session["UserName"].ToString()
            </ text >
        }*@
    </fieldset>
<h2>UserDashboard</h2>

This behavior seams to be some error in the model validation.这种行为似乎是模型验证中的一些错误。

Debug the Post Login action and see if the ModelState.IsValid is really valid and if it is showing any error.调试登录后操作并查看ModelState.IsValid是否真的有效以及是否显示任何错误。

[Update] [更新]

I think the problem is that in your form you are passing only Username and Password .我认为问题在于,在您的表单中,您只传递了UsernamePassword When it enters the login action, ModelState.IsValid will be false because in your model you have UserId , Email and Confirm Password .当它进入登录操作时, ModelState.IsValid将为 false 因为在您的模型中您有UserIdEmailConfirm Password Try to add this code before If(ModelState.IsValid)尝试在If(ModelState.IsValid)之前添加此代码

ModelState.Remove("UserId"); 
ModelState.Remove("Email"); 
ModelState.Remove("ConfirmPassword");

I think the code is moving to "return View(objUser)" due to null.我认为由于空值,代码正在转向“返回视图(objUser)”。 Check once are you getting any data while retrieving "var".在检索“var”时检查一次您是否获得了任何数据。

There was a some issue with database and in the model that i had created.数据库和我创建的模型存在一些问题。 i deleted the model and recreated the model with updated database which has an error.我删除了模型并使用有错误的更新数据库重新创建模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM