Tuesday, October 25, 2016

How to pass parameter to partial view and capture the value(s) in partial view


Main View

Html.RenderPartial("_PartialViewName"new ViewDataDictionary(ViewData){ { "one", Model.One }, { "two", Model.Two } });

-------------------------- 

Controller

public ActionResult _PartialViewName()
{
return PartialView();
}

--------------------------

How to get parameter values in partial view

@{
    var one = (string)ViewData["one"];
    var two = (string)ViewData["two"];

}

Tuesday, August 23, 2016

Add new Column in Existing Table


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS         
WHERE TABLE_NAME = 'tblName' AND COLUMN_NAME = 'ColumnName')         
BEGIN         
  ALTER TABLE tblName ADD ColumnName nvarchar(60)        
END

Wednesday, August 17, 2016

Generic Repository Pattern & Unit of Work Repository Pattern Using (DI)


HomeController:-

public class HomeController : Controller
{
   private IUnitOfWork _unitOfWork;

   public HomeController(IUnitOfWork unitOfWork)
   {
       _unitOfWork = unitOfWork;
   }

   public ActionResult Index()
   {
Category modelList = _unitOfWork.RepositoryFor<Category>().GetById(5);
var objResult = _unitOfWork.RepositoryFor<Category>().GetAll();
return View(modelList);
   }
}

IUnitOfWork:-

public interface IUnitOfWork
{        
    IGenericRepository<T> RepositoryFor<T>() where T : class;
    void SaveChanges();
}

UnitOfWork:-

public class UnitOfWork : IUnitOfWork, System.IDisposable
{
     private readonly NORTHWNDEntities _context;
      
     public UnitOfWork(NORTHWNDEntities context)
     {
         _context = context;
     }
 
     public IGenericRepository<T> RepositoryFor<T>() where T : class
     {
         return new GenericRepository<T>(_context);
     }
 
     public void SaveChanges()
     {
         _context.SaveChanges();
     }
 
     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);
         System.GC.SuppressFinalize(this);
     }
 }
IGenericRepository:-
public interface IGenericRepository<TEntity>
{
   TEntity GetById(object id);
   TEntity GetFirstOrDefault(
   void Insert(TEntity entity);
   void Update(TEntity entity);
   void Delete(object id);
   List<TEntity> GetAll();
}
GenericRepository:-
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where 
TEntity : class
{
    private DbContext context;
    private DbSet<TEntity> dbSet;
    public GenericRepository(DbContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }  
    public virtual TEntity GetById(object id)
    {
        return dbSet.Find(id);
    }

    public virtual TEntity GetFirstOrDefault(Expression<Func<TEntity, bool>>   
filter = nullparams Expression<Func<TEntity, object>>[] includes)
    {
        IQueryable<TEntity> query = dbSet;
        foreach (Expression<Func<TEntity, object>> include in includes)
               query = query.Include(include);
        return query.FirstOrDefault(filter);
    }

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Update(TEntity entity)
    {
        dbSet.Attach(entity);
        context.Entry(entity).State = EntityState.Modified;
    }
    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }
    public virtual List<TEntity> GetAll()
    {
       return dbSet.ToList<TEntity>();
    }
 }

Tuesday, July 19, 2016

How to add multiple css values into Style in MVC

@{
string color = "black";
if (Model[i].RevenueRecovered.HasValue && Model[i].RevenueRecovered.Value < 0)
{
color = "red";
       }
}

new { @style = string.Format("width:100%; color:{0}", @color) }

Wednesday, February 17, 2016

Async and Await


Controller Side Implementation

[OutputCache(Duration = 0)]
 public async Task<JsonResult> BindAll()
 {
var Task1 = _res.Task1().ConfigureAwait(false);
var Task2 = _res.Task2().ConfigureAwait(false);
var Task3 = _res.Task3().ConfigureAwait(false);
var resTask1 = (await Task1).OrderBy(t => t.Id).ToList();
var resTask2 = (await Task2).OrderBy(t => t.Id).ToList();
var resTask3 = (await Task3).OrderBy(t => t.Id).ToList();

return Json(new
{
resTask1,
     resTask2,
     resTask3
}, JsonRequestBehavior.AllowGet);

}

Web.API Implementation

public async Task<List<ClassName>> GetAll(int value)
{
var apiUrl = string.Format("{0}/api/ControllerName/GetAll/{1}", _ServiceName, value);
       using (var client = new HttpClient())
       {
           var response = await client.GetAsync(apiUrl);
              if (!response.IsSuccessStatusCode)
                   return null;
                return await response.Content.ReadAsAsync<List<ClassName>>();
       }
}


[Route("GetAll/{value}")]
public IHttpActionResult GetAll(int value)
{
var results = _service.GetAll(value);
       if (results == null || results.Count == 0)
           return NotFound();
            else
              return Ok(results);
}


public async Task<List<ClassName>> GetAllValues(Model objFilter)
{
var apiUrl = string.Format("{0}/api/ControllerName/GetAllValues/", _ServiceName);
       using (var client = new HttpClient())
       {
           var response = await client.PostAsJsonAsync(apiUrl, objFilter);
              if (!response.IsSuccessStatusCode)
                  return null;
              return await response.Content.ReadAsAsync<List<ClassName>>();
       }
}


[HttpPost]
[Route("GetAllValues")]
public IHttpActionResult GetAllValues(Model objFilter)
{
var results = _service.GetAllValues(objFilter);
       if (results == null || results.Count == 0)
            return NotFound();
       else
            return Ok(results);
}