Friday 21 July 2017

Export in database data to excel in MVC

For xlsx formart

Install-package EPPlus from manage nugget package. It writes Excel 2007/2010 files using the Open Office Xml format (xlsx) only.



var data = (from a in db.Tables select a).ToList();
            ExcelPackage excel = new ExcelPackage();
            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
   //workSheet.Cells[1, 1].LoadFromDataTable(myDataTable, true);
            workSheet.Cells[1, 1].LoadFromCollection(data, true);
            using (var memoryStream = new MemoryStream())
            {
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=Contact.xlsx");
                excel.SaveAs(memoryStream);
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }


For xls formart

 For xls formart no need to add any package .


var data = (from a in db.Tables select a).ToList();
            var grid = new System.Web.UI.WebControls.GridView();
            grid.DataSource = data;
            grid.DataBind();
            Response.Clear();
            Response.Buffer = true;
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Charset = "";         
            StringWriter strwritter = new StringWriter();
            HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=FileName.xls");         
            grid.RenderControl(htmltextwrtter);
            Response.Write(strwritter.ToString());
            Response.End();



Thursday 20 July 2017

Image Upload in mvc

@model MvcApplication1.Models.ABCmodel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
    <fieldset>
        <legend>Image</legend>
        <input type="file" name="FileUpload" id="imgInp" onchange="loadFile(event)" />
        <img id="output"  height="150" width="150" />
        <input type="submit" name="Submit" id="Submit" value="Upload" formaction="/Demo/Upload" formenctype="multipart/form-data" />     
    </fieldset>
   
}
<script>   
    function loadFile(event) {
        debugger;
            var output = document.getElementById('output');
            output.src = URL.createObjectURL(event.target.files[0]);
    }
</script>




public ActionResult Index()
        {          
            return View();
        }
[HttpPost]
        public ActionResult Upload()
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
                    string relativePath = "~/Images/" + fileName;
                    file.SaveAs(path);
                                   }
            }
            return View("Index");
        }



Calender in Mvc

@model MvcApplication1.Models.ABCmodel

@{
    ViewBag.Title = "Calender";
}
@using (Html.BeginForm())
{
    @Html.TextBoxFor(model => model.Date,   new { @class = "datefield", type = "date" })  
}

In controller

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





Autocomplete Textbox in MVC

@model MvcApplication1.Models.ABCmodel
@{
    ViewBag.Title = "AutocompleteTxt";
   // Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-group">
        <div class="col-md-4">
            @Html.TextBoxFor(model => model.Name, htmlAttributes: new { @class = "form-control" })
        </div>      
    </div>
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/start/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
    debugger
    $(document).ready(function () {
        $("#Name").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/AllControl/GetCountries",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Name, value: item.Name };
                        }))

                    }
                })
            },
        });
    })
</script>


In Controller

  public ActionResult AutocompleteTxt()
        {
            return View();
        }
        [HttpPost]
        public JsonResult GetCountries(string Prefix)
        {
            var Countries = (from c in db.Tables
                             where c.Name.StartsWith(Prefix)
                             select new { c.Name, c.Id });
            return Json(Countries, JsonRequestBehavior.AllowGet);
        }