Click here to Skip to main content
15,878,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all. I'm very new in MVC and hope to explain my problem as well.
I have a Login box(in _Login.cshtml file) in all of my pages which is called directly through the _layout.cshtml file in the @Html.Partial("_Login",model) form. In index page of my Home controller, I retrieve all comments from database and list them in index view. In browser at first everything goes well. All comments are listed and loginbox is appeared in left side of page. But when i enter incorrect Username or Password,the error message is rendered from _Login action,but all comments are disappeared. Obviously this is because the index page doesn't load after error message fired.Please guide me how can do this such that i have both comments and fired error message.
Appreciate any help.These are my codes.
//_Layout.cshtml
C#
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="refresh" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
    <div id="loginbox" >       
   @Html.Partial("_Login",new CSS_Test.ViewModels.CommentViewModel())                     
    </div>
    <div id="first_head">
        <span class="times"> @{Html.RenderAction("TimeSummary","Home");}</span>
    </div>
</body>

//_Login.cshtml in Shared folder
C#
@model CSS_Test.ViewModels.CommentViewModel       
@using (Html.BeginForm("_LogIn", "Account",FormMethod.Post,new{id="login", @class="enter_form"} ))
    {

        if (@Session["UserName"]==null)
        {
        @Html.TextBoxFor(m =>this.Model.LogModel.UserName, new { @class="UserName", placeholder = "Username" ,autofocus="autofocus",@Autocomplete= "off"})    
       <br />
        @Html.ValidationMessageFor(m => this.Model.LogModel.UserName)    
        <BR />
        @Html.PasswordFor(m => this.Model.LogModel.Password, new { @class = "Password", placeholder = "Password" })
        <br/>       
            @Html.ValidationMessageFor(m => this.Model.LogModel.Password)       
        <BR />    
        <div style="color:#f00;font-weight:bold" id="kkk">
            @if (ViewData.ModelState["Error"]!=null) {               
                   @Html.ValidationMessage("Error")           
               }
          </div>
       }
        if (@Session["UserName"] != null)
        {   
     <div style="color:#4cff00;font-weight:bold;direction:rtl">
      @Session["UserName"] welcome <br />
         <div>@Html.ActionLink("Logout","LogOff","Account")</div>
         </div>
            if (Request.UrlReferrer != null) { 
                if (@Request.Url.AbsoluteUri.ToString().Contains("Account"))            
            {
         <div style="padding-removed7px; ">
         <a href="@Url.Action("Put_Comment", "admin", new { UserName = @Session["UserName"] })">Administrator Part</a>
             </div>
       }
       }
        }
       if (@Session["UserName"] == null)
        {
        <br />
        @Html.CheckBoxFor(m => this.Model.LogModel.RememberMe)
        @Html.LabelFor(m => this.Model.LogModel.RememberMe)
        <BR />
        <input type="submit"  value="Submit" class="btn btn-primary" />
            
       }
    }
</div>

//_Login Action in Account Controller
C#
[HttpPost]
public ActionResult _LogIn(CSS_Test.ViewModels.CommentViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.LogModel.UserName, model.LogModel.Password))
        {

            FormsAuthentication.SetAuthCookie(model.LogModel.UserName, model.LogModel.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }

            @Session["UserName"] = model.LogModel.UserName;

        }

        ViewData.ModelState.AddModelError("Error", "Incorrect Username Or Password");
                  }

    return View(model);
}

and finally index action
<pre lang="c#">
 public ActionResult Index()
        {               
            MyContext mydb =new MyContext("MyContext");
                var All_Comments = mydb.Comments.ToList<Comment>();

                CommentViewModel mymodel = new CommentViewModel()
                {
                    all_comments=All_Comments
                };
            return View(mymodel);           
                }
Posted

1 solution

Thank you all friends to put many comments for help me!!!!
But i founded that i need to use Jquery script to submit the form using $.ajax function to _Login action.Here is my change codes.
//_Layout.cshtml
C#
@model CSS_Test.ViewModels.CommentViewModel       
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js"></script>
<script>
    $(document).ready(function () {
        $("#submit").click(function () {           
            $.ajax({
                type: "Post",
                url: "Account/_Login",
                data: $("#all_form").serialize(),
                error: function (xhr, status, error) {
                    alert("Error,Something went wrong");
                },
                success: function (data) {
                    if (data.Err_message != null)
                        $("#invalid_user").html(data.Err_message);
                }
                
            })

        });
   
    });

</script>
@using (Html.BeginForm(null,null,FormMethod.Post,new{id="all_form"}))
    { 
        <div>
        @{

        if (@Session["UserName"] == null)
        {
                <div id="User">
        @Html.TextBoxFor(m => this.Model.LogModel.UserName, new { @class = "UserName", placeholder = "UserName", autofocus = "autofocus", @Autocomplete = "off" })    
     </div>
       <br />
              @Html.ValidationMessageFor(m => this.Model.LogModel.UserName)    
        <br />
        @Html.PasswordFor(m => this.Model.LogModel.Password, new { @class = "Password", placeholder = "Password" })
        <br />       
            @Html.ValidationMessageFor(m => this.Model.LogModel.Password)       
        <br />    
        <div style="color:#f00;font-weight:bold" id="invalid_user">          
          </div>
        }
        if (@Session["UserName"] != null)
        {
   
     <div style="color:#4cff00;font-weight:bold;direction:rtl">
      @Session["UserName"] WelCome<br />
         <div>@Html.ActionLink("LogOut", "LogOff", "Account")</div>
         </div>
            if (Request.UrlReferrer != null)
            {
                if (@Request.Url.AbsoluteUri.ToString().Contains("Account"))
                {
         <div style="padding-top:7px; ">
         <a href="@Url.Action(" put_comment=", " admin=", new { UserName = @Session[" username="] })">Administrator Part</a>
             </div>
                }
            }
        }
        if (@Session["UserName"] == null)
        {
        <br />
        @Html.CheckBoxFor(m => this.Model.LogModel.RememberMe)
        @Html.LabelFor(m => this.Model.LogModel.RememberMe)
        <br />
         <input type="button" value="submit" id="submit"/>
            
        }
    }
</div>
    }

//my _Login action
C#
   [HttpPost]
public ActionResult _LogIn(CSS_Test.ViewModels.CommentViewModel model, string returnUrl)
{
    Json_Res result = new Json_Res();
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.LogModel.UserName, model.LogModel.Password))
        {

            FormsAuthentication.SetAuthCookie(model.LogModel.UserName, model.LogModel.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            @Session["UserName"] = model.LogModel.UserName;
            result.Comment_VM = model;
        }

        result.Err_message = "Invalid UserName Or Password";
                   }

    return Json(result,JsonRequestBehavior.AllowGet);
}

// And this is Json_Res class Viewmodel
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CSS_Test.Models;

namespace CSS_Test.ViewModels
{
    public class Json_Res
    {
        public string Err_message { get; set; }
        public CommentViewModel Comment_VM { get; set; }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900