Buscar contenidos

jueves, 31 de mayo de 2018

Una forma de administrar Error en Global.asax


void Application_Error(object sender, EventArgs e)
        {
            Exception err = Server.GetLastError();

            if (err != null)
            {
                if (HttpContext.Current.Server != null)
                {
                    Response.Clear();

                    string data = @"
                    <div style='text-align:center; font-size:15px;'>
                        <img src='url.png' style='margin: 0 auto;' alt='' />                 
                    <hr>
                    <a href='/Home/Index'>Volver a pantalla de búsqueda</a>
                    </div>
                    ";

                    Response.Write(data);

                    Server.ClearError();
                }
            }
        }

miércoles, 30 de mayo de 2018

Passing Multiple Models Using AJAX In ASP.NET MVC






@model PassingMultipleModel.Models.Common
@{
    ViewBag.Title = "Index";
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h2>Customer</h2>
<table>
    <tr><td>Customer Id</td><td>@Html.TextBoxFor(m => m.customer.CustomerId)</td></tr>
    <tr><td>Customer Name</td><td>@Html.TextBoxFor(m => m.customer.CustomerName)</td></tr>
    <tr><td>Address</td><td>@Html.TextBoxFor(m => m.customer.Address)</td></tr>
</table>

<h2>Employee</h2>
<table>
    <tr><td>Employee Id</td><td>@Html.TextBoxFor(m => m.employee.EmployeeId)</td></tr>
    <tr><td>Employee Name</td><td>@Html.TextBoxFor(m => m.employee.EmployeeName)</td></tr>
    <tr><td>Address</td><td>@Html.TextBoxFor(m => m.employee.Address)</td></tr>
</table>
<input type="button" id="btnClick" value="Submit" />
<script>
    $("#btnClick").click(function () {

      
        var customer = {
            CustomerId: $('#@Html.IdFor(m=>m.customer.CustomerId)').val(),
            CustomerName: $('#@Html.IdFor(m=>m.customer.CustomerName)').val(),
            Address: $('#@Html.IdFor(m=>m.customer.Address)').val()
        }
        var employee = {
            EmployeeId: $('#@Html.IdFor(m=>m.employee.EmployeeId)').val(),
            EmployeeName: $('#@Html.IdFor(m=>m.employee.EmployeeName)').val(),
            Address: $('#@Html.IdFor(m=>m.employee.Address)').val()
        }

        var model = {
            "customer": customer,
            "employee": employee
        }

        //alert(model)
        $.ajax({
            type: "post",
            url: "/Demo/Process",
            data: model,
            datatype: "json",
            cache: false,
            success: function (data) {
                alert(data);
            },
            error: function (xhr) {
                alert('No Valid Data');
            }
        });


    });
</script>

Controller------------------------------------------------------

public JsonResult Process(Common model)
{
           
     // Write your code based on your Process or your Concept
     return Json("Hola Mundo",JsonRequestBehavior.AllowGet);
}


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

https://www.aspsnippets.com/Articles/Pass-Send-Model-object-in-jQuery-ajax-POST-request-to-Controller-method-in-ASPNet-MVC.aspx

     function SendModel() {


            var person = {};

            person.Name = $("#txtName").val();

            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{person: ' + JSON.stringify(person) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });



        }



        $("#test").click(function () {

            SendModel();


        });





        [HttpPost]
        public JsonResult AjaxMethod(PersonModel person)
        {
            person.DateTime = DateTime.Now.ToString();

            return Json(person);

        }




lunes, 28 de mayo de 2018

Grid.MVC

http://mvcgrid.net/


MVCGrid.Net

A grid for ASP.NET MVC and Bootstrap with ajax paging and sorting. Also has filtering support, export to csv, back button support, and graceful degradation.
The primary goal of this project is to provide the core grid functionality, along with a very simple and easy-to-use client-side API to allow you to easily add the additional front-end interaction you need. You can add it to your project very easily and get it running with minimal effort, but it also has the extensibility to customize when needed.
You configure your grids on app start, and provide a function callback to actually query your data. The library will handle the ajax requests. It will parse and validate the requested options and then pass the QueryOptions to your function to retrieve the data.

public static class MVCGridConfig
    {
        public static void RegisterGrids()
        {

            MVCGridDefinitionTable.Add("Filtering", new MVCGridBuilder<Solicitud>()
             .WithAuthorizationType(AuthorizationType.AllowAnonymous)
             .AddColumns(cols => {

                cols.Add("ViewLink").WithSorting(false)
                .WithHeaderText("Ver")
                .WithHtmlEncoding(false)
                .WithValueExpression((p, c) => c.UrlHelper.Action("Solicitud", "Home", new { id = p.Id }))               
                .WithValueTemplate("<a href='{Value}' ><span class='glyphicon glyphicon-folder-open'></span></a>");

                 cols.Add("Id").WithHeaderText("Id").WithSorting(true).WithFiltering(true)
                .WithValueExpression(p => p.Id.ToString());

                cols.Add("Titulo").WithHeaderText("Título").WithValueExpression(p => p.Titulo)
                .WithFiltering(true).WithSorting(true);

                cols.Add("FCreacion").WithHeaderText("Fecha de creación").WithValueExpression(p => p.FechaCreacion.ToShortDateString())
                .WithFiltering(true);

                 cols.Add("Hit").WithHeaderText("Vistas").WithValueExpression(p => p.Hit.ToString())
              .WithFiltering(false).WithSorting(false);

                 cols.Add("Ir").WithSorting(false)
               .WithHeaderText("Link")
               .WithHtmlEncoding(false)
               .WithValueExpression((p, c) => p.UrlContenido)
               .WithValueTemplate("<a href='{Value}'  target='_blank' ><span class='glyphicon glyphicon-send'></span></a>");
                
             })
             .WithSorting(true, "Id")
             .WithPaging(true, 10, true, 10)
             .WithFiltering(true)
             .WithRetrieveDataMethod((context) => {

                 var options = context.QueryOptions;

                 Solicitud solicitudObj = new Solicitud();

                 List<Solicitud> ListSolicitud = new List<Solicitud>();

                ListSolicitud = solicitudObj.Get(Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["RowsPerPage"]),
                Convert.ToInt32(((options.PageIndex == null) | (options.PageIndex == 0)) ? 1 : (options.PageIndex + 1)),
                (options.SortDirection == SortDirection.Unspecified ? "DESC" : options.SortDirection.ToString().Contains("A") ? "ASC" : "DESC"),
                options.SortColumnName,
                (options.Filters.Count == 0 ? "" : options.Filters.First().Value),
                (options.Filters.Count == 0 ? "" : options.Filters.First().Key));

                return new QueryResult<Solicitud>()
                {
                    Items = ListSolicitud,
                    TotalRecords = ListSolicitud.Count == 0 ? 0 : ListSolicitud.First().TotalVirtual
                    };
                    })
                );
        }
    }


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

<script src="~/Scripts/bootstrap.min.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/MVCGridHandler.axd/script.js"></script>
    <script src="~/Scripts/jquery.cookie.js"></script>
    <script src="~/Scripts/jquery.masked-input.min.js"></script>

    <style type="text/css">
        * {
            font-family: Arial;
        }

        .well {
            background: #E6E6E6;
        }

        table {
            background: white;
        }
    </style>

    <script type="text/javascript">

        function Main() {

            $("#MVCGrid_Loading_Filtering").html('<img src="Images/loading.gif" />');

            $(".col-xs-6").each(function () {
                if ($(this).text().match('Showing')) {
                    $(this).text($(this).text().replace("to", "a"));
                    $(this).text($(this).text().replace("of", "de"));
                    $(this).text($(this).text().replace("Showing", "Mostrando"));
                    $(this).text($(this).text().replace("entries", " registros"));
                }
            });

            $("span").each(function () {
                if ($(this).text().match('Previous')) {
                    $(this).text($(this).text().replace("« Previous", "<<"));
                } else
                    if ($(this).text().match('Next »')) {
                        $(this).text($(this).text().replace("Next »", ">>"));
                    }
            });

            $("th").each(function () {
                if ($(this).text().match('Ver')) {
                    $(this).css("width", "10px");
                } else if ($(this).text().match('Id')) {
                    //$(this).css("width", "50px");
                }

            });
        }

        $().ready(function () {

            Main();

            $(document).ajaxComplete(function () {
                Main();
            });

        });


    </script>