简体   繁体   中英

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. 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. 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.

[Update]

I think the problem is that in your form you are passing only Username and Password . When it enters the login action, ModelState.IsValid will be false because in your model you have UserId , Email and Confirm Password . Try to add this code before 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. Check once are you getting any data while retrieving "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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