Monday 16 October 2017

redirect grid data to another page in mvc using kendo ui

redirect grid data to another page in kendo mvc  using ajax post

in view
when we click on edit button it will go to another view with its row id.
columns.Command(command => command.Custom("Edit").Click("editDetails")).Width(120);
<script type="text/javascript">

    //......................<Edit>............
    function editDetails(e) {
        debugger
        var dataItem = this.dataItem($(e.target).closest("tr"));
        var id = dataItem.CompetitorId;
        location.href = "@Url.Action("", "Controllername/viewname")?Id="+id
    }
</script>
Another view page
In view
<script>
    $(document).ready(function () {
        debugger
        var baseUrl = (window.location).href; // You can also use document.URL
        var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
     
        $.ajax({
            //type: "GET",
            type: 'POST',
            url: "/Crm_Competitor/GetDetailById",
            data: { id: koopId },
            //   contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (data) {
                debugger;
                document.getElementById("CompetitorId").value = data.CompetitorId;
            },

        });
      
    });

</script>

In controller

public ActionResult GetDetailById([DataSourceRequest]DataSourceRequest req,int id)
        {
            try
            {
                Detail = new CompetitorDetail();
                var request = new RestRequest("api/CompetitorDetail/" + id, Method.GET) { RequestFormat = DataFormat.Json };

                var response = _client.Execute<List<CompetitorDetail>>(request);

                if (response.Data == null)
                    throw new Exception(response.ErrorMessage);

                return Json(response.Data.ToList()[0]);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

Video upload in mvc using kendo ui


these two code need to add in web.config to order set max length 100mb
====
<configuration> 
... 
<system. web>

<httpRuntime maxRequestLength="102400" executionTimeout="3600" />

...

</system .web>

</configuration>
===========
<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="104857600"/>
        </requestFiltering>
    </security>
</system.webServer> 
In view
<body>
    <div>
        <video id="output" width="400" controls="controls">
            <source src="#" type="video/mp4">
        </video>
        @(Html.Kendo().Upload()
                    .Name("files").Multiple(false)
                            .Events(events => events
                        .Select("onSelect"))
                    .Async(a => a
                        .Save("Save", "Video") .AutoUpload(true))
        )
    </div>
</body>
<script>
    function onSelect(e) {
        debugger
        var output = document.getElementById('output');
        output.src = URL.createObjectURL(event.target.files[0]);
    }
</script>

In controller
public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
        {          
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    //var fileName = Path.GetFileName(file.FileName);
                    //var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                    var fileName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Images"), fileName);
                    var fileExtension = Path.GetExtension(file.FileName);
                    Session["Path"] = "~/Images/" + fileName;
                    file.SaveAs(physicalPath);
                }
            }
            // Return an empty string to signify success
            return Content("");
        }

Reference


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();