MVC

Create a custom autocomplete control in ASP.NET MVC

How to create a custom HTML control in ASP.NET MVC?

using System;
using System.Web.Mvc;


namespace MvcApplication1.Helpers
{
     public static class LabelExtensions
     {
          public static string Label(this HtmlHelper helper, string target, string text)
          {
               return String.Format("", target, text);
          }
     }
}

Refer link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs

Auto complete custom control: Download

 

Put/Delete http verb not working server

Please add following code in web.cofig file.


<system.webServer>
		<modules>
			<remove name="WebDAVModule"/>
			<remove name="FormsAuthentication" />
			<remove name="ApplicationInsightsWebTracking" />
			<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
		</modules>
		<handlers>
			<remove name="WebDAV" />
			<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
			<remove name="OPTIONSVerbHandler" />
			<remove name="TRACEVerbHandler" />
			<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
		</handlers>

If not solve then please follow link.

Generate and Download PDF file on Ajax Post method, C#

Requirements: On ajax post, save data to database, generate invoice and download as PDF file. There are many open source packages available to generate PDF file. So I’m not going describe that using which paid/free package is used to generate PDF file. I am going to describe the trick how can download the generated PDF file without saving on hard drive.

HomeController.CS


public class HomeController : Controller
    {
        public ActionResult Index()
        {         
            return View();
        }

        public ActionResult Download()
        {
            //using (var ms = new MemoryStream())
            //{
                //using (var document = new Document(PageSize.A4, 50, 50, 15, 15))
                //{
                //    PdfWriter.GetInstance(document, ms);
                //    document.Open();
                //    document.Add(new Paragraph("HelloWorld"));
                //    document.Close();
                //}
                //Response.Clear();
                ////Response.ContentType = "application/pdf";
                //Response.ContentType = "application/octet-stream";
                //Response.AddHeader("content-disposition", "attachment;filename= Test.pdf");
                //Response.Buffer = true;
                //Response.Clear();
                //var bytes = ms.ToArray();
                //Response.OutputStream.Write(bytes, 0, bytes.Length);
                //Response.OutputStream.Flush();
           // }

            return View();
        }

        [HttpPost]
        public ActionResult Save()
        {

// write code here to save the data in database. 
            var fName = string.Format("MYPDF-{0}.pdf", DateTime.Now.ToString("s"));
            using (var ms = new MemoryStream())
            {
                using (var document = new Document(PageSize.A4, 50, 50, 15, 15))
                {
                    PdfWriter.GetInstance(document, ms);
                    document.Open();
                    document.Add(new Paragraph("HelloWorld"));
                    document.Close();
                }

                var bytes = ms.ToArray();              
                Session[fName] = bytes;
            }

            return Json(new { success = true, fName }, JsonRequestBehavior.AllowGet);
            //return View();
        }
         public ActionResult DownloadInvoice(string fName)
         {
             var ms =  Session[fName] as byte[] ;
             if(ms == null)
                 return new EmptyResult();
             Session[fName] = null;
             return File(ms, "application/octet-stream", fName);
         }
    }

Index.cshtml

 <input type="button" id="btnSave" value="Save & Download PDF" />
 
 $(document).ready(function () {
 $("#btnSave").click(function () {
 $.ajax({
 type: 'POST',
 url: "/home/save",
 dataType: "json",
 success: function (resultData)
 {
 if (resultData.success) {
 window.location = "/home/DownloadInvoice" + "?fName=" + resultData.fName;
 }
 }
 });
 })
 })
 

On ajax post method, data will save into the database. Here Save is a post method. Check the HomeController.CS file. Generate file and save an array of byte in Session. In JSON result, send the name of file. Ajax post method retrieve the data and using window.location send request to server to download the file. Now, check DownloadInvoice method in HomeController.cs.

Thank you for reading this post.

Selected value not set on DropDownListFor() in MVC

Let me tell you small story.

There is a ‘title’ column name for salutation in database. Based on that, I create a view model so property name is ‘title’ and list name is ‘titles’. Due to property name is ‘title’, selected value is not set on DropdownListFor. Because ‘title’ is a reserved keyword. It is an attribute of any html element.

I renamed property name in viewmodel ‘title’ to ‘salutation’. All is working fine..

Enjoy day 🙂

UnitOfWork Generic Repository

The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD).

UnitOfwork


  public class UnitOfWork : IUnitOfWork
    {
        public DataBaseEntities _context;

        #region Constructor
        public UnitOfWork()
        {
            _context = new DataBaseEntities ();
        }
        #endregion

        #region Implement Inteface Methods

        public void Commit()
        {
            _context.SaveChanges();
        }

        public void CommitAndRefreshChanges()
        {
            bool saveFailed = false;

            do
            {
                try
                {
                    _context.SaveChanges();
                    saveFailed = false;
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    saveFailed = true;

                    ex.Entries.ToList()
                              .ForEach(entry =>
                              {
                                  entry.OriginalValues.SetValues(entry.GetDatabaseValues());
                              });

                }
            } while (saveFailed);
        }

        public void RollbackChanges()
        {
            // set all entities in change tracker 
            // as 'unchanged state'
            _context.ChangeTracker.Entries()
                              .ToList()
                              .ForEach(entry => entry.State = System.Data.Entity.EntityState.Unchanged);
        }

        public IEnumerable ExecuteQuery(string sqlQuery, params object[] parameters)
        {
            return _context.Database.SqlQuery(sqlQuery, parameters);
        }

        public int ExecuteCommand(string sqlCommand, params object[] parameters)
        {
            return _context.Database.ExecuteSqlCommand(sqlCommand, parameters);
        }

        private bool _disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this._disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

  public List ExecuteQueryForDropdown(string sqlQuery)
        {
            var result = db.Database.SqlQuery(sqlQuery).ToList();
            return result;
        }

 public IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 50)
        {
            int skipCount = index * size;
            var resetSet = filter != null ? table.Where(filter).AsQueryable() : table.AsQueryable();
           
            total = resetSet.Count();


            if (!string.IsNullOrEmpty(orderByColumnName))
            {
                resetSet = resetSet.OrderBy(orderByColumnName, ascending);
                resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
            }
            return resetSet.AsQueryable();
        }

        #region Repositories

        #endregion
    }

Interface of UnitOfWork


 public interface IUnitOfWork : IDisposable
    {
        /// 
        /// Commit all changes made in a container.
        /// 
        void Commit();

        /// 
        ///  If the entity have fixed properties and any optimistic concurrency problem exists,
        ///  then 'client changes' are refreshed - Client wins
        /// 
        void CommitAndRefreshChanges();

        /// 
        /// Rollback tracked changes. See references of UnitOfWork pattern
        /// 
        void RollbackChanges();

        /// 
        /// Execute specific query with underliying persistence store
        /// 
        /// Entity type to map query results
        /// 
        /// SELECT idCustomer,Name FROM dbo.[Customers] WHERE idCustomer > {0}
        /// 
        /// 
        /// 
        /// 
        IEnumerable ExecuteQuery(string sqlQuery, params object[] parameters);

        /// 
        /// Execute arbitrary command into underliying persistence store
        /// 
        /// 
        /// Command to execute
        /// 
        /// SELECT idCustomer,Name FROM dbo.[Customers] WHERE idCustomer > {0}
        /// 
        ///
        /// A vector of parameters values
        /// The number of affected records
        int ExecuteCommand(string sqlCommand, params object[] parameters);

 List ExecuteQueryForDropdown(string sqlQuery);

        IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 20);
    }

Generic Repository


 public class RepositoryBase where T : class
    {
        internal TSPEntities _dataContext;
        internal DbSet _dbset;

        public RepositoryBase(TSPEntities context)
        {
            this._dataContext = context;
            this._dbset = context.Set();
        }

        /// 
        /// Paging Query with filter
        /// 
        /// 
        /// 
        /// 
        /// 
        public virtual List Get(Expression<Func> filter = null, Func<IQueryable, IOrderedQueryable> orderBy = null, string includeProperties = "")
        {
            IQueryable query = _dbset;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        /// 
        /// Get selected records with paging
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public virtual IEnumerable GetPaged(int pageIndex, int pageCount, System.Linq.Expressions.Expression<Func> orderByExpression, bool ascending)
        {
            var set = _dbset;

            if (ascending)
            {
                return set.OrderBy(orderByExpression)
                          .Skip(pageCount * pageIndex)
                          .Take(pageCount);
            }
            else
            {
                return set.OrderByDescending(orderByExpression)
                          .Skip(pageCount * pageIndex)
                          .Take(pageCount);
            }
        }

        public virtual void Add(T entity)
        {
            _dbset.Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _dbset.Remove(entity);
        }

        public virtual void Delete(Expression<Func> where)
        {
            IEnumerable objects = _dbset.Where(where).AsEnumerable();
            foreach (T obj in objects)
                _dbset.Remove(obj);
        }

        public virtual T GetById(long id)
        {
            return _dbset.Find(id);
        }

        public virtual T GetById(string id)
        {
            return _dbset.Find(id);
        }

        public virtual IEnumerable GetAll()
        {
            return _dbset.ToList();
        }

        public virtual IQueryable GetAllQueryable()
        {
            return _dbset.AsQueryable();
        }

        public virtual IEnumerable GetMany(Expression<Func> where)
        {
            return _dbset.Where(where).ToList();
        }

        public virtual IQueryable GetManyQueryable(Expression<Func> where)
        {
            return _dbset.AsQueryable().Where(where);
        }

        public T Get(Expression<Func> where)
        {
            return _dbset.Where(where).FirstOrDefault();
        }

 public IQueryable Filter(Expression<Func> filter, string orderByColumnName, bool ascending, out int total, int index = 0, int size = 50)
        {
            int skipCount = index * size;
            var resetSet = filter != null ? table.Where(filter).AsQueryable() : table.AsQueryable();
           
            total = resetSet.Count();


            if (!string.IsNullOrEmpty(orderByColumnName))
            {
                resetSet = resetSet.OrderBy(orderByColumnName, ascending);
                resetSet = skipCount == 0 ? resetSet.Take(size) : resetSet.Skip(skipCount).Take(size);
            }
            return resetSet.AsQueryable();
        }
    }

how to read resource file in jquery or javascript or js file

As generally we do in asp.net project, I have created a global resource file for storing common error messages, info messages, labels etc in my first MVC4 project. I used ready-made validation.js for giving validation. I have face the problem how to get the resource file’s object value in .js file. From come out this problem I have find a way. I had create a controller ‘ResoruceScript’. And added below code in ActionResult method.

        public ActionResult Index()
        {
            Response.Clear();            
            Response.ContentType = "text/javascript";
            
            return View();
        }

Then create a view for “Index” Action. And remove the html content, all tags which are added by default when we create a new view. And below code.


        @using System.Collections
@using System.Globalization
@using System.Resources
@using Pharma
@{
    Layout = null;
    // Get a set of resources appropriate to the culture defined by the browser
    ResourceSet resourceSet = @Resources.PharmaCore.ResourceManager.GetResourceSet
        (CultureInfo.CurrentUICulture, true, true);
}

// Define the empty object in javascript
var Resources = {};
@foreach (DictionaryEntry res in resourceSet)
{
    // Create a property on the javascript object for each text resource
    @:Resources.@res.Key = "@Html.Raw(
        HttpUtility.JavaScriptStringEncode(res.Value.ToString()))";
}

Here, PharmaCore is my resource file name. Above code create the array of resource file’s objects. Add this view as javascript file in head tag or anywhere in the page but before the use of resource value. I have added in head tag of page.

 <script src="~/ResourceScript"&gtl</script>

Now, you are able to get the resource file’s object value as ‘Resources.rfv_Common_Msg’ in .js file.

How to add reference System.Web.Optimization

The Microsoft.Web.Optimization package is now obsolete. With the final release of ASP.NET (MVC) 4 you should install the Microsoft ASP.NET Web Optimization Framework:

Install the package from nuget:

Right click on References, Select Manage Nuget Packages. Type Microsoft.AspNet.Web.Optimization in search box and press enter you will get the package. Click on install.

Create and configure bundle(s) in App_Start\BundleConfig.cs:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles) {
        bundles.Add(new ScriptBundle("~/Scripts/jquery").Include(
            "~/Scripts/Lib/jquery/jquery-{version}.js",
            "~/Scripts/Lib/jquery/jquery.*",
            "~/Scripts/Lib/jquery/jquery-ui-{version}.js")
        );

        bundles.Add(new ScriptBundle("~/Scripts/knockout").Include(
             "~/Scripts/Lib/knockout/knockout-{version}.js",
             "~/Scripts/Lib/knockout/knockout-deferred-updates.js")
        );
    }
}

Call the RegisterBundles() function from Application_Start() in your global.asax.cs:

using System.Web.Optimization;

protected void Application_Start() {
     ...
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     ...
}

In your view.cshtml include the Optimization namespace and render the bundle(s):

@using System.Web.Optimization

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