Menu ▼

Home / blogs / Dotnet / MVC /

This example shows you how to disable the page local caching in mvc asp.net. To disable page local caching we can write the below code by overriding OnActionExecuting method in controller instead of writing in each view in controller (or you can write in a common controller and each controller will be inherited from that common controller).

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
    filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
    filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    filterContext.HttpContext.Response.Cache.SetNoStore();
}
Read More...
Submited By : mrkraju On 08 Nov 2015

This example shows you how to create login page and validating user details in MVC using entity frame work.

Output :

Implementation:
You can download the sample project from here.... Download
  1. Create Database and name it as "sample"
  2. Run the below Query to create table "tblUser"
    GO

    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE [dbo].[tblUser](
        [UserID] [int] IDENTITY(1,1) NOT NULL,
        [UserName] [nvarchar](50) NULL,
        [Password] [nvarchar](50) NULL,
     CONSTRAINT [PK_tblUser] PRIMARY KEY CLUSTERED 
    (
        [UserID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, 
    ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

  3. Add sample user details
  4. In the project solution under Model add LoginModel.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    namespace MVCEntityLogin.Models
    {
        public class LoginModel
        {
            [Required(ErrorMessage = "Please enter user name.")]
            [DataType(DataType.EmailAddress)]
            [Display(Name = "User Name")]
            [StringLength(30)]
            public string UserName { get; set; }

            [Required(ErrorMessage = "Please enter password.")]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            [StringLength(10)]
            public string Password { get; set; }

        }

        [Table("tblUser")]
        public class tblUser
        {
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int UserID { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
        }
    }
  5. Under Controllers add HomeController.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MVCEntityLogin.Models;

    namespace MVCEntityLogin.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }

            public ActionResult Login()
            {
                return View();
            }

            [HttpPost]
            public ActionResult Login(LoginModel login)
            {
                if (ModelState.IsValid)
                {
                    DBEntity db = new DBEntity();
                    var user = (from userlist in db.tblUsers
                                where userlist.UserName == login.UserName && userlist.Password == login.Password
                                select new
                                {
                                    userlist.UserID,
                                    userlist.UserName
                                }).ToList();
                    if (user.FirstOrDefault() != null)
                    {
                        Session["UserName"] = user.FirstOrDefault().UserName;
                        Session["UserID"]=user.FirstOrDefault().UserID;
                        return Redirect("/home/welcomepage");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid login credentials.");
                    }
                }
                return View(login);
            }

            public ActionResult WelcomePage()
            {
                return View();
            }
        }
    }

  6. Now add the Views under Views->Home
    Login.cshtml
    @model MVCEntityLogin.Models.LoginModel
    @{
        ViewBag.Title = "Login";
    }
    <h2>
        Login</h2>
    @using (Html.BeginForm())
    {
        
        @Html.ValidationSummary(true)
           
        <div style="border: solid 1px #ccc; padding: 30px 0 30px 30px; border-radius: 5px;
            width: 325px; margin: auto; display: table;">
            <table>
                <tr>
                    <td valign="top">
                        @Html.LabelFor(model => model.UserName)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.UserName)
                        <div style="height: 20px;">@Html.ValidationMessageFor(model => model.UserName)
                        </div>
                    </td>
                </tr>
                <tr>
                    <td valign="top">
                        @Html.LabelFor(model => model.Password)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.Password)
                        <div style="height: 20px;">@Html.ValidationMessageFor(model => model.Password)
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <input type="submit" value="Login" />
                    </td>
                </tr>
            </table>
        </div>
    }
    WelcomePage.cshtml
    @{
        ViewBag.Title = "WelcomePage";
    }
    <h2>
        Welcome : @Session["UserName"].ToString()</h2>

You can download the sample project from here.... Download
Read More...
Submited By : mrkraju On 16 Oct 2014

We can enable or disable the client side validations in MVC4 by doing simple configuration / code changes.

For enable / disable validations application level:

We can use any one of the below two methods (web.config change or Global.asax.cs change)

Configuration change in web.config

<appSettings>

  <add key="ClientValidationEnabled" value="true" />

  <add key="UnobtrusiveJavaScriptEnabled" value="true" />

</appSettings>

 

Code change in Global.asax.cs file

protected void Application_Start()

{

    HtmlHelper.ClientValidationEnabled = true;

    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

}

 

For enable/disable validation in a particular view 

set the below two properties in the View Razor code.

@{

    ViewBag.Title = "Index";

    HtmlHelper.ClientValidationEnabled = true;

    HtmlHelper.UnobtrusiveJavaScriptEnabled = true;                                 

}

 

Note:

In addition to the above changes for enable the client side validations we need to add the JQuery, jquery.validate, jquery.validate.unobtrusive js file reference in bundleconfig.cs and we have to consume them in the view.

Ex: 

BundleConfig.config:

public static void RegisterBundles(BundleCollection bundles)

{

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

                "~/Scripts/jquery-{version}.js"));

 

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(

                "~/Scripts/jquery.unobtrusive*",

                "~/Scripts/jquery.validate*"));

}

 

In View Razor code at bottom:

@Scripts.Render("~/bundles/jquery")

@Scripts.Render("~/bundles/jqueryval")

 

 

Read More...
Submited By : mrkraju On 14 Apr 2014




Search dotnetlearners.com