Saturday, 29 December 2018

Creating helper popup in MVC5 to fill textbox itemname and description

Creating helper popup to select and fill item name and description on type item name on textbox as shown in figure below:






using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace msPoojaElectrical.Models.Material
{
    [Table("ItemMaster")]
    public class ItemMasterModel
    {
        public Int32 ITEM_APP_UNIT { get; set; }
        [Key]
        public Int64 ITEM_ID { get; set; }
        public string ITEM_CODE { get; set; }
        public string ITEM_NAME { get; set; }
        public string ITEM_DESC { get; set; }
        public string ITEM_RATE { get; set; }
        public string ITEM_QTY { get; set; }
        public string ITEM_STATUS { get; set; }

        public string ITEM_OPRLOG { get; set; }
        [NotMapped]
        public double ITEM_AMT { get; set; }
        [NotMapped]
        public string PopId { get; set; }
        [NotMapped]
        public string PopName { get; set; }
        [NotMapped]
        public List<SelectListItem> ddlItemType { get; set; }
    }
}

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

using msPoojaElectrical.Controllers;
using msPoojaElectrical.Models.Material;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace msPoojaElectrical.Areas.Material.Controllers
{
    public class ItemMasterController : BaseController
    {
        // GET: Material/ItemMaster
     
     
        public ActionResult CreateItem()
        {
         
            return View();
        }

        [HttpPost]
        public ActionResult CreateItem(ItemMasterModel itemMasterModel)
        {
         
            return View();
        }
     
    }

}

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

@model msPoojaElectrical.Models.Material.ItemMasterModel

@{
    ViewBag.Title = "CreateItem";
    Layout = "~/Views/Shared/_LayoutNew.cshtml";
}

<style>
    #modalPopup {
        top: -425px;
        z-index: 99999999;
    }
</style>

<h2 class="text-center">Create Item</h2>
<br />
@using (Html.BeginForm("CreateItem", "ItemMaster", FormMethod.Post, new { @id = "formCreateItem" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.PopId, new { htmlAttributes = new { @value = "txtItemCode", @id = "PopId" } })
    @Html.HiddenFor(model => model.PopName, new { htmlAttributes = new { @value = "txtItemDesc", @id = "PopName" } })
    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        <div class="form-group">
            @Html.LabelFor(model => model.ITEM_CODE, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.ITEM_CODE, new { htmlAttributes = new { @class = "form-control", @id = "txtItemCode", @onkeyup = "ShowItemCode();" } })
                @Html.ValidationMessageFor(model => model.ITEM_CODE, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ITEM_NAME, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.ITEM_NAME, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ITEM_NAME, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ITEM_DESC, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.ITEM_DESC, new { htmlAttributes = new { @class = "form-control", @id = "txtItemDesc" } })
                @Html.ValidationMessageFor(model => model.ITEM_DESC, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ITEM_RATE, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.ITEM_RATE, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ITEM_RATE, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.ITEM_QTY, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.ITEM_QTY, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ITEM_QTY, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.ITEM_AMT, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.ITEM_AMT, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ITEM_AMT, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="row">
            <div class="col-md-7 text-center">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div class="text-center">
    @Html.ActionLink("Back to List", "Index")
</div>

<script>
    $(document).ready(function () {
        $("#modalPopup").hide();
        $("#PopId").val('txtItemCode');
        $("#PopName").val('txtItemDesc');
    });

    function ShowItemCode() {

        debugger;
        var App_Unit = '@Request.RequestContext.HttpContext.Session["App_Unit"]';
        if (App_Unit == 0)
            App_Unit = 1;
        $.ajax({
            url: '@Url.Action("ItemHelper", "MasterHelp", new { area = ""})',
            data: {
                TableName: "ItemMaster",
                CodeField: "Item_Code",
                DescField: "Item_Desc",
                Condition: "Where Item_Code like '" + $("#txtItemCode").val().toUpperCase() + "%'"
            },
            type: "get"
        }).done(function (response) {
            $("#exampleModelLabel").html("");
            $("#exampleModelLabel").html("ItemCode");
            $("#modalBody").html(response);
            $("#modalPopup").show();
            $("#modalPopup").removeClass("fade");
        });
    };
</script>

---------------------------------------------------------------------------
In Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace msPoojaElectrical.Models
{
    public  class RawQuery
    {
        public class MasterHelp
        {
            public string Code { get; set; }
            public string Description { get; set; }
        }
    }
}


In MasterHelp Controller


using msPoojaElectrical.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using static msPoojaElectrical.Models.RawQuery;

namespace msPoojaElectrical.Controllers
{
    public class MasterHelpController : Controller
    {
        // GET: MasterHelp
        DataAccess db = new DataAccess();
        string strSql = "";
        public ActionResult ItemHelper(string TableName, string CodeField, string DescField, string Condition)
        {
            strSql = "Select " + CodeField + " as Code, " + DescField + " as Description from " + TableName + " "+ Condition;
            List<MasterHelp> data = db.Database.SqlQuery<MasterHelp>(strSql).ToList();
           // return PartialView("_ItemHelper",data);
            return PartialView("_Index",data);
        }
    }
}

---------------------------------------------------------------------------------
In Partial View _Index

@model List<msPoojaElectrical.Models.RawQuery.MasterHelp>

<script type="text/javascript">
    // todo ; uncomment
    //$(document.ready(function () {
    //    var Table = $('.HelpTableClass').DataTable({
    //        "ScrollY": "350px",
    //        "ScrollCollaspe": true,
    //        lengthChange: true
    //    });
    //}));

</script>
@*<script src="~/Content/Assets/js/jquery-2.1.4.min.js"></script>*@
@*<script src="~/Content/Assets/js/jquery-2.1.4.min.js"></script>*@
<style>
    /*TODO :*/
    /*Get Css for web grid*/
</style>


@{
    var grid = new WebGrid(source: Model, canPage: false, rowsPerPage: 20, ajaxUpdateContainerId: "gridContent");
}
<div id="gridContent">
    @grid.GetHtml(htmlAttributes: new { id = "HelpTable" },
                                        tableStyle: "HelpTableClass table table-striped table-bodered",
                                        headerStyle: "thead th-lg",
                                        columns: grid.Columns(grid.Column(columnName: "Code", header: "Code"),
                                                             grid.Column(columnName: "Description", header: "Description")
                                        ))
</div>

<script type="text/javascript">
    // todo ; uncomment
    //$(document).ready(function () {
    //    $("#gridContent a").removeAttr("href");
    //});

    $("#HelpTable").on('click', 'tbody > tr > td', function () {
     
        //var Id = $("#PopId").val();
        //var Name = $("#PopName").val();
        var Id = "txtItemCode";
        var Name = "txtItemDesc";

        //var Id2 = $("#ConId").val();
        //var Name2 = $("#ConName").val();
        var rowIndex = $(this).parent().html();
        //$("#modalPopup").modal('hide');
        $("#modalPopup").hide();
        $("#modalPopup").addClass("fade");

        var currentRow = $(this).closest("tr");
        var col1 = currentRow.find("td:eq(0)").html();
        var col2 = currentRow.find("td:eq(1)").html();
     
        $("#" + Id + "").val(col1);
        $("#" + Id + "").focus();
        if (Name != "") {
            $("#" + Name + "").val(col2);
            $("#" + Name + "").focus();
        }
     

        //$("#" + Id2 + "").val(col1);
        //$("#" + Id2 + "").focus();
        //if (Name2 != "") {
        //    $("#" + Name2 + "").val(col2);
        //    $("#" + Name2 + "").focus();
        //}

        $("#ConId").val('');
        $("#ConName").val('');
        $("#" + Id + "").trigger("change");
    });
</script>

-----------------------------------------------------------------------------------
In _LayoutNew

 <!---//End-da-slider----->


    <div id="modalPopup" class="modal-dialog fade" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <div class="modal-header">
                <h4 class="modal-title" id="exampleModelLabel"></h4>
            </div>
            <div class="modal-body" id="modalBody">
                @*<div class="wthree-info">
                 
                </div>*@
                <div class="row">
                    <div>
                        <div class="table-responsive"></div>
                    </div>
                </div>
                <div class="clearfix"></div>
            </div>
        </div>
    </div>

Crystal Report In MVC5

                                                                       
Working with crystal report using Xml as data source in mvc :

1. Install Crystal Report
2. Copy aspnet_client folder to your project and it is not required to include this folder into the project. Let it be excluded.
3. Report folder contains all the project related reports.
4. Schema folder contains XML file which is being used here as data source.
5. We will be creating datatable in our code containing same data or column and datatype like string, double, datetime etc in xml file. Datetime and Double should be defined in column using typeof in order to show data in proper format in report.
6. Session parameter in crystal report viewer should in same order as in parameter of crystal report.
7. Check for folder permission if there is any issues in crystal report viewer data showing.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace msPoojaElectrical.Models.Material
{
    [Table("ItemMaster")]
    public class ItemMasterModel
    {
        public Int32 ITEM_APP_UNIT { get; set; }
        [Key]
        public Int64 ITEM_ID { get; set; }
        public string ITEM_CODE { get; set; }
        public string ITEM_NAME { get; set; }
        public string ITEM_DESC { get; set; }
        public string ITEM_RATE { get; set; }
        public string ITEM_QTY { get; set; }
        public string ITEM_STATUS { get; set; }

        public string ITEM_OPRLOG { get; set; }
        [NotMapped]
        public double ITEM_AMT { get; set; }
        [NotMapped]
        public string PopId { get; set; }
        [NotMapped]
        public string PopName { get; set; }
        [NotMapped]
        public List<SelectListItem> ddlItemType { get; set; }
    }
}

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

using msPoojaElectrical.Controllers;
using msPoojaElectrical.Models.Material;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace msPoojaElectrical.Areas.Material.Controllers
{
    public class ItemMasterController : BaseController
    {
        // GET: Material/ItemMaster
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(ItemMasterModel itemMasterModel)
        {
            // TODO ; Show Items list using item master
            return View();
        }
     
        public ActionResult CreateItem()
        {
         
            return View();
        }
        [HttpPost]
        public ActionResult CreateItem(ItemMasterModel itemMasterModel)
        {
         
            return View();
        }
        public JsonResult GetItemReport(string itemId, string itemCode, string itemAppUnit)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("address", typeof(string));
            dt.Columns.Add("city", typeof(string));
            dt.Columns.Add("country", typeof(string));

            DataRow dr = dt.NewRow();
            dr["name"] = "bbb";
            dr["address"] = "bbb";
            dr["city"] = "bbb";
            dr["country"] = "bbb";
            dt.Rows.Add(dr);

            if (dt.Rows.Count > 0)
            {
                string companyName = "MSPoojaElectricals";
                string documentName = "Item Report";
                HttpContext.Session["RptName"] = "CrystalReport1.rpt";
                HttpContext.Session["ReportData"] = dt;
                HttpContext.Session["CompanyName"] = companyName;
                HttpContext.Session["FormName"] = documentName;
                //return "1";
                return Json("1", JsonRequestBehavior.AllowGet);
            }
            return Json("0", JsonRequestBehavior.AllowGet);

        }
    }
}

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


@model msPoojaElectrical.Models.Material.ItemMasterModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutNew.cshtml";
}

<div class="main">
    <div class="project-wrapper">
        @*TODO: Add hidden field for popupid and name*@
        <div class="wrap">
            <div class="contact">
                <div class="cont span_2_of_contact col-md-offset-3">
                    <h5 class="leave text-center">Item Master</h5>
                    <div class="clear"></div>
                    @*@using (Html.BeginForm("Login", "Login", FormMethod.Post))
                    {*@

                        @Html.HiddenFor(model => model.PopId, new { @Value = "txtItemCode" })
                        @Html.HiddenFor(model => model.PopName)
                        <div class="contact-to">
                            @Html.TextBoxFor(model => model.ITEM_CODE, new { @placeholder = "Enter User Name", @class = "form-control", id = "txtItemCode" })
                            <span class="input-group-text pointer" id="basic-addon2" onclick="javascript: return ShowItemCode();"><i class="fa fa-filter"></i>Help?</span>

                            @Html.TextBoxFor(model => model.ITEM_NAME, new { @placeholder = "Enter User Name", @class = "form-control", id = "txtItemName" })
                            @Html.TextBoxFor(model => model.ITEM_DESC, new { @placeholder = "Enter User Name", @class = "form-control", id = "txtItemDesc" })
                        </div>
                        @*<input id="btnLogin" formaction="@Url.Action("Search")" type="submit" class="btn-primary btnPrint" value="Save">*@
                    <input id="btnLogin" type="submit" class="btn-primary btnPrint" value="Save">




                    @*}*@
                </div>

                <div class="clear"></div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">

    $(".btnPrint").click(function () {
        alert("hi");
        var itemId = $(this).attr('item_Id');
        var itemCode = $(this).attr('itemCode');
        var itemAppUnit = $(this).attr('itemAppUnit');

        $.ajax({
            url: "/Material/ItemMaster/GetItemReport",
            type: "get",
            data: {
                itemId: itemId,
                itemCode: itemCode,
                itemAppUnit: itemAppUnit
            },
            success: (function (result) {
                alert(result);
                if (result == "1") {
                    window.open('/Reports/ReportViewer.aspx', '_blank');
                }
                else if (result == "-1") {
                    swal("Error", "Please try later.", "error");
                }
                else {
                    swal("Warning", "No Data", "warning");
                }
            })
        });
    });
</script>


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

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReportViewer.aspx.cs" Inherits="msPoojaElectrical.Reports.ReportViewer" %>

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" EnableDrillDown="false"
                HasToggleGroupTreeButton="false" ToolPanelView="None" OnUnload="CrystalReportViewer1_Unload" HasRefreshButton="True"
                PrintMode="ActiveX" />
        </div>
    </form>
</body>

</html>

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace msPoojaElectrical.Reports
{
    public partial class ReportViewer : System.Web.UI.Page
    {
        ReportDocument crystalReport;
        protected void Page_Load(object sender, EventArgs e)
        {
            CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
            crystalReport = new ReportDocument();

            string RptName = Session["RptName"].ToString();
            Session["RptLogo"] = "";

            switch (RptName)
            {
                case "CrystalReport1.rpt":
                    crystalReport.Load(Server.MapPath(@"\Reports\" + RptName));
                    crystalReport.SetDataSource(Session["ReportData"]);
                    crystalReport.SetParameterValue(0, Session["CompanyName"]);
                    crystalReport.SetParameterValue(1, Session["FormName"]);
                    crystalReport.SetParameterValue(2, Session["RptLogo"]);

                    break;

            }
            CrystalReportViewer1.ReportSource = crystalReport;
            CrystalReportViewer1.DataBind();
        }

        protected void CrystalReportViewer1_Unload(object sender, EventArgs e)
        {
            crystalReport.Close();
            crystalReport.Dispose();
        }
    }
}

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

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="SchItems"
    targetNamespace="http://tempuri.org/SchItems.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/SchItems.xsd"
    xmlns:mstns="http://tempuri.org/SchItems.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="SchItems">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="address" type="xs:string"/>
        <xs:element name="city" type="xs:string"/>
        <xs:element name="country" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>