Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Tuesday, June 7, 2016

How to apply Typeahead with ASP.Net MVC using Ajax Source


Twitter typeahead javascript library is a fast and fully-featured autocomplete library inspired by the autocomplete search functionality from twitter.
Following script is HTML code for defining input with typeahead. Note there is one
data-provide="typeahead" defined within the input node. This attribute notifies the plugin that we are going to perform a lookup with this textbox.
<div class="col-md-3 col-xs-6">
    <label for="StudentID" class="control-label">Enter Student ID</label>
    <div id="details"></div>
    <div class="input-group input-group-sm">
        <input type="text" name="studentId" id="studentId" class="form-control input-sm" data-provide="typeahead">
    </div>
</div>

Javascript part:
$("#studentId").typeahead({
    minLength: 4,
    source: function (query, process) {
        var students = [];
        map = {};

        // This is going to make an HTTP post request to the controller
        return $.post('/Student/StudentLookup', {studentId: query}, function (data) {
            // Loop through and push to the array
            $.each(data, function (i, student) {
                map[student.Name] = student;
                students.push(student.Name);
            });
            // Process the details
            process(students);
        });
    },
    updater: function (item) {
        var studentId = map[item].StudentId;
        // Set the text to our selected id
        $("#details").text("Selected : " + studentId);
        return item;
    }
});

Controller Part:
public class StudentController : Controller
{
  public ActionResult StudentLookup()
  {
    var students = new List<StudentEntity>
        {
            new StudentEntity {StudentId = "01", Name = "Frank Zhang"},
            new StudentEntity {StudentId = "02", Name = "Andrew Chen"},
            new StudentEntity {StudentId = "03", Name = "John Smith"},
            new StudentEntity {StudentId = "03", Name = "Johnson Stone"},
        };
    return Json(students, JsonRequestBehavior.AllowGet);
  }
}
Reference:
https://github.com/bassjobsen/Bootstrap-3-Typeahead
http://www.deanhume.com/Home/BlogPost/twitter-bootstrap-typeahead-and-asp-net-mvc---key-value-pairs/88

Tuesday, April 5, 2016

Creating PDF using Pdfmake - Introduction

Pdfmake follows a declarative approach. You don't need to calculate positions manually like: writeText(text, x, y), moveDown etc..., as you other libraries do.

You just need to create document-definition-object like this:
var docDefinition = { content: 'This is an sample PDF printed with pdfMake' };

You can add more stuffs to the object with multi-level tables, images, lists, paragraphs, margins, styles etc.  After you made the object, you can create the pdf and download it.

// open the PDF in a new window
pdfMake.createPdf(docDefinition).open();
// print the PDF (not working in this version, will be added back in a couple of days)
// pdfMake.createPdf(docDefinition).print();
// download the PDF
pdfMake.createPdf(docDefinition).download();

Pdfmake has following features:
  • line-wrapping,
  • text-alignments (left, right, centered, justified),
  • numbered and bulleted lists,
  • tables and columns
    • auto/fixed/star-sized widths,
    • col-spans and row-spans,
    • headers automatically repeated in case of a page-break,
  • images and vector graphics,
  • convenient styling and style inheritance,
  • page headers and footers:
    • static or dynamic content,
    • access to current page number and page count,
  • background-layer
  • page dimensions and orientations,
  • margins,
  • custom page breaks,
  • font embedding,
  • support for complex, multi-level (nested) structures,
  • helper methods for opening/printing/downloading the generated PDF.
  • setting of PDF metadata (e.g. author, subject)
Source: 

Tuesday, March 22, 2016

Applying Node.js in ASP.Net MVC 4.5

Node.js is a server side javascript framework which mainly used for real time web application. The core idea is event driving with asynchronous programming. When  you develop your dashboard web applications, it's so great to let your web page to show real time charts and statistic data. There is also real time programming framework named Signal R from Microsoft, which is purely under ASP.Net and a great contender compared with Node.js.

Compared with Signal R, Node.js has another feather that all javascript code you wrote for client side can be easily reused on the server side.  When I worked with a Online Web Reporting project, I applied Chart.js javascript to create vivid charts on the front web end, and also I applied jsPDF javascript library on client side to create PDF report for those vivid charts. All these worked fine but we also have a requirement that the server side can create same PDF reports and deliver them to our client's email. To make those PDF reports have same look and feel, the server side should call the same client side javascript code to create the PDF doc. The difference is the server side service will not be launched from client web side. And Node.js offered great chance to show their shinning part for sharing same client code on server side.

So we finally choose Node.js, to do above 2 great jobs.

The following blog link would compare Node.js and Signal R.
http://sim4all.com/blogging/?p=454

Sunday, January 31, 2016

How to handle ASP.NET MVC JSON Result Date Format Issue

ASP.Net MVC controller will return JsonResult for action so that ajax can handle those Json data. But Json data has issues for type DateTime, especially Microsoft SQL Server DB. Here is some result if you just display those data in string format: "/Date(-501361200000)/". This is one very popular topic for ASP.Net MVC Json data processing. You can process those Json DateTime at client side using some Javascript tricks. But the best solution is on the Server side, you can use Json.Net from newtonsoft to do the magic.

This is one typical action method in controller:
        public JsonResult GetStudent(string name)
        {
            try
            {
                if (name == null)
                {
                    return Json(null, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    using (StudentService _service = new StudentService())
                    {
                        Student = _service.GetStudent(name);
                        return Json(model, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
You don't need to change above code. What you should do is:
First,  add a new class CustomJsonResult which inherits from JsonResult.
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class CustomJsonResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}
Second, in your Base Controller, override Json method to return CustomJsonResult.
        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new CustomJsonResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
        }
Then all JsonResult call in your controller will return CustomJsonResult I created above, which use Newtonsoft.Json.Converters.IsoDateTimeConverter as serializer instead, and you will see the readable DateTime instead of annoying and wild date format in JsonResult.

Source:
http://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format

Wednesday, November 4, 2015

How to applying Store Procedures to build Entity Framework in ASP.Net MVC project


After you have successfully build your Entity Framework, you can update it if your tables or store procedures have been changed. Right click on the Entity Framework model in your solution explorer, choose Open, and click on Model Browser. Then right click on the root node of the model, and choose Update Model from Database, the data model will be updated. If you changed the database connection string in web.config, and create a new database connection using different connection name, the Model Browser will start a new wizard to connect to the new database. In this way you can switch different database for the predefined Entity Framework.

Source:
http://weblogs.asp.net/dotnetstories/using-stored-procedures-with-entity-framework-in-an-asp-net-application
http://beyondrelational.com/modules/2/blogs/64/posts/11620/entity-framework-40-bind-stored-procedure-with-result-entity-class.aspx