Search This Blog

Saturday, 13 May 2017

Unable to use strongly-typed views when using PagedList in MVC


Index.cshtml


Controller Action Method that returning a PagedList

public ActionResult Index(int? page)
        {
            BusinessLayer businessLayer = new BusinessLayer();
            List<FileUploadModel> fileUploadModel = businessLayer.GetDocument(search).ToList();
            int pageSize = 5;
            int pageNumber = (page ?? 1);
            return View(fileUploadModel.ToPagedList(pageNumber, pageSize));
        }

FileUploadModel class that containing the form propery

public class FileUploadModel
    {
        public string DocumentTitle { getset; }
        public string FileName { getset; }
    }


Solution:

Step 1:- Add IPagedList<FileUploadModel> property in FileUploadModel class.

using PagedList;

public class FileUploadModel
    {
        public string DocumentTitle { getset; }
        public string FileName { getset; }
        public IPagedList<FileUploadModel> iPagedUpdList { setget; }

    }

Step 2:- Change controller Action method

Note:- Instead of returning the paged list, return an object of this view model.

public ActionResult Index(int? page)
        {
            BusinessLayer businessLayer = new BusinessLayer();
            FileUploadModel fileUploadModel = new FileUploadModel();
            int pageSize = 5;
            int pageNumber = (page ?? 1);
            fileUploadModel.iPagedUpdList = businessLayer.GetDocument().ToPagedList(pageNumber, pageSize);
            return View(fileUploadModel);
        }

Step 3:- Change view


























Use Model.iPagedUpdList property to render the list of documents.

@foreach (var item in Model.iPagedUpdList)
{
    <tr>
        <td>@item.DocumentTitle</td>                    
        <td>@item.FileName</td>                    
    </tr>
}

instead of

@foreach (var item in Model)
{
    <tr>
        <td>@item.DocumentTitle</td>                    
        <td>@item.FileName</td>                    
    </tr>
}

Wednesday, 19 April 2017

How to access session variables in Web API Controller in ASP.Net MVC

Step 1:- Create SessionHttpControllerHandler class under Global.asax.cs

using System.Web.Http.WebHost;
using System.Web.SessionState;

    public class SessionHttpControllerHandler   : HttpControllerHandlerIRequiresSessionState
    {
        public SessionHttpControllerHandler(RouteData routeData)
            : base(routeData)
        {
        }
    }

Step 2:- Create SessionHttpControllerRouteHandler class under  Global.asax.cs

public class SessionHttpControllerRouteHandler : HttpControllerRouteHandler
    {
        protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new SessionHttpControllerHandler(requestContext.RouteData);
        }
    }

Step 3:- Create SessionHttpControllerRouteHandler class under  Global.asax.cs

public class SessionHttpControllerRouteHandler : HttpControllerRouteHandler
    {
        protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new SessionHttpControllerHandler(requestContext.RouteData);
        }
    }

Step 4:- Open WebApiConfig.cs under App_Start folder and Comment following Code

 public static void Register(HttpConfiguration config)
        {
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
        }

Step 5:- Open RouteConfig.cs under App_Start folder and Copy Past highlighted code

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
               ).RouteHandler = new SessionHttpControllerRouteHandler(); 

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Question", action = "Index", id = UrlParameter.Optional }
            );
        }

Step 6:- Api Controller

 public class TestController : ApiController
    {
        public string Get()
        {
            var session = System.Web.HttpContext.Current.Session;
            if (session != null)
            {
                // Add Your Code here
            }
            return "No Session Exists";
        }
    }

Note:-

It's not compulsory to create a class in Global.asax.cs file. You can also add in model.

Tuesday, 4 April 2017

ORA-20000: ORU-10027: buffer overflow, limit of 10000 bytes

PL/SQL Version 12c

This error occurred when I am trying to print the output of cursor to output window where output window default buffer size is 10000 bytes and cursor returning more than 20000 records.

DECLARE
  vCur      SYS_REFCURSOR;
  Column1   VARCHAR2(30);
BEGIN
  OPEN vCur FOR
    SELECT Column1 FROM TEST t;
    DBMS_OUTPUT.ENABLE(500000);
  LOOP
    FETCH vCur
      INTO Column1;
    EXIT WHEN vCur%NOTFOUND;
    dbms_output.put_line(Column1);
  END LOOP;
END;

Use following to increse buffer size in query statement.
-- Number is used to increse buffer size as specified number
DBMS_OUTPUT.ENABLE(500000);

-- NULL is used to increse buffer size unlimited
DBMS_OUTPUT.ENABLE(NULL);

Note:-
1. Depending on Oracle version, DBMS_OUTPUT has different default buffer size.
2. Its reduces the query performance, after analyzing output result comment DBMS_OUTPUT line in Store Procedure.

Saturday, 1 April 2017

ViewModel returns null on postback mvc 4

Make sure controller action method parameter object name not match with any its property.

This is model
public class QuestionModel
{
      [Required]
      public string Question getset; }
}

This is Controller Action method
[HttpPost]
public ActionResult Create(QuestionModel Question)
{
      //Add your code here
}

Create method parameter 
QuestionModel Question object name matching with its property Question.
In this case when we post data from view to controller ViewModel returns null.

Sunday, 26 March 2017

Regenerate session id in asp.net

protected void ReGenerateSessionId()
        {
            SessionIDManager manager = new SessionIDManager();
            string oldId = manager.GetSessionID(Context);
            string newId = manager.CreateSessionID(Context);
            bool isAdd = false, isRedir = false;
           
            manager.RemoveSessionID(Context);

            manager.SaveSessionID(Context, newId, out isRedir, out isAdd);

            HttpApplication ctx = (HttpApplication)HttpContext.Current.ApplicationInstance;
            HttpModuleCollection mods = ctx.Modules;
            System.Web.SessionState.SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
            System.Reflection.FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            SessionStateStoreProviderBase store = null;
            System.Reflection.FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;

            SessionStateStoreData rqItem = null;

            foreach (System.Reflection.FieldInfo field in fields)
            {
                if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
                if (field.Name.Equals("_rqId")) rqIdField = field;
                if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
                if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;

                if ((field.Name.Equals("_rqItem")))
                {
                    rqItem = (SessionStateStoreData)field.GetValue(ssm);
                }
            }
            object lockId = rqLockIdField.GetValue(ssm);

            if ((lockId != null) && (oldId != null))
            {
                store.RemoveItem(Context, oldId, lockId, rqItem);
            }

            rqStateNotFoundField.SetValue(ssm, true);
            rqIdField.SetValue(ssm, newId);
        }