簡體   English   中英

提交表單后在 ASP.NET MVC 中。 它不會重定向到其他頁面。 它正在加載相同的頁面

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

1.在ASP.NET MVC中注冊成功后,在登錄時輸入用戶名和密碼等字段,然后點擊提交按鈕。 2.它不是登錄,也不是重定向到另一個頁面,但它實際上看起來像刷新頁面,並且在單擊提交 btn 后會出現用戶名輸入的數據。 我的控制器

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");*/
            }
        }
    }
}

我的登錄

@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")
}

我的用戶


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; }

    }
}

用戶儀表板

@{
    ViewBag.Title = "UserDashboard";
}

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

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

這種行為似乎是模型驗證中的一些錯誤。

調試登錄后操作並查看ModelState.IsValid是否真的有效以及是否顯示任何錯誤。

[更新]

我認為問題在於,在您的表單中,您只傳遞了UsernamePassword 當它進入登錄操作時, ModelState.IsValid將為 false 因為在您的模型中您有UserIdEmailConfirm Password 嘗試在If(ModelState.IsValid)之前添加此代碼

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

我認為由於空值,代碼正在轉向“返回視圖(objUser)”。 在檢索“var”時檢查一次您是否獲得了任何數據。

數據庫和我創建的模型存在一些問題。 我刪除了模型並使用有錯誤的更新數據庫重新創建模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM