Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

2012-12-12

Web Api: Passing a Complex type in JSON

,

In one project i wanted to pass a complex type to the Post method of an Web Api controller. The Post itself will be done using JQuery in the JSON format. I noticed that the parameter was always null. After a bit of searching i found the solution.

The Set Up

Server side

public class ValuesController : ApiController
{
// POST api/values
public void Post(MyComplexType value)
{
}
}

public class MyComplexType
{
public string Name { get; set; }

public MyComplexSubType MyComplexSubType { get; set; }
}

public class MyComplexSubType
{
public int Age { get; set; }
}

Client Side

 <script type="text/javascript">

function
MyComplexSubType()
{
var self = this;

self.Age = 26;
}

function MyComplexType()
{
var self = this;

self.Name =
"Kenny Tordeur";
self.MyComplexSubType =
new MyComplexSubType();
}


function PostComplexType()
{
$.ajax(
"/api/values", {
data: JSON.stringify(
new MyComplexType()),
contentType:
'application/json',
type:
'POST',
success: SendComplexTypeCallBack
});
}


function SendComplexTypeCallBack(data)
{
alert(
"Complex type sended");
}
</script>

The PostComplexType will be trigged by a click event on a button. It will create a javascript object called MyComplexType. This object will map directly to the object we created on the server side.


 


image


The missing link


With this set-up the parameter will always be null. We need to add a line of code to the global.asax.

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

 


Value providers are used by the model binding system in MVC to populate the values of model objects. We basically add a provider that enables to bind a model to a JSON model.  The solution can be downloaded here.

Read more →

2012-12-07

WebApi: File upload and download using JQuery and submit button

,

I am going to create a WebApi service called FileService that can be used to upload and download files. The service will only contain 2 methods. A Post to upload and a Get method that accepts an id parameter to identify the file that needs to be downloaded. Let’s start with the Post method.

The Post method

This method will look in the Request object to see if there are any posted files. If so, it will loop over the files and create them on the server side. The server will return a 201 HttpStatus and a list of strings that will contain the full path of the file(s) at server side. When there are no files posted, the service will return a 401 status a.k.a. BadRequest.

public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;

// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();

// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs( filePath);

files.Add(filePath);
}

// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}

return result;
}

The Get Method


As mentioned before, the Get Method will accept a string file that will identify (= filename) the file that needs to be downloaded.

public HttpResponseMessage Get(string id)
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("~/" + id);

// check if parameter is valid
if (String.IsNullOrEmpty(id))
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
// check if file exists on the server
else if (!File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{// serve the file to the client
result = Request.CreateResponse( HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = id;
}

return result;
}

Uploading a File


Using a submit  button

 <form name="form1" method="post" action="api/file" enctype="multipart/form-data">
<
div>
<
label>
Using submit</label>
<
input name="myFile" type="file" />
</
div>
<
div>
<
input type="submit" value="Submit" />
</
div>
</
form>


Using JQuery

<form enctype="multipart/form-data">
<
label>
Using JQuery</label>
<
input name="file" type="file" />
<
input type="button" id="Upload" value="Upload" />
</
form>
        <script type="text/javascript">
$(function () {
$('#Upload').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: 'api/file',
type: 'POST',
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
});
});
</script>

Downloading a File


image


Summary


The solution can be downloaded here.

Read more →

2012-12-01

Paged Grid with Knockout.js and WebApi

,
I want to see how easily you can create a custom grid that uses an WebApi as datasource and that allows the user to page the data and also allow them to choose a page size for the grid.

The WebApi

The WebApi will return a viewmodel that contains an array of names (string) and a property that specifies how many pages that there are available.
    public class NamesGridViewModel
    {
        public IEnumerable<String> Names { get; set; }

        public int NumberOfPages { get; set; }
    }

The WebApi itself will contain a method that accepts 2 parameters. The parameters will be page (the page that we request) and pagesize (how many entries a page contains). This method will be responsible for calculating how many pages there are and to serve the requested names based on the 2 parametes.
    public class ValuesController : ApiController
    {
        public IList<String> Names
        {
            get { return new List<String> { "Fred", "Barney", "Betty", "Wilma", "Bart", "Lisa", "Maggie", "Homer", "Marge" }; }
        }
            
        public NamesGridViewModel Get(int page, int pagesize)
        {
            return new NamesGridViewModel
                       {
                           // get the request names for the specific page
                           Names = (0 == page? null : Names.Skip((page - 1)*pagesize).Take(pagesize).ToArray())
                           ,
                           // calculated number of pages and ceil the value
                           NumberOfPages = ((int) Math.Ceiling((double) Names.Count/pagesize))
                       };
        }
    }

The client


The client will need a reference to kockout.js. With knockout.js it is possible to apply the MVVM pattern and also work with templates in javascript.


The UI

Page size: <select data-bind="options: availablePageSize, optionsText: $data, value: selectedPageSize"></select><!-- the grid --><table data-bind="with: namesGridViewModel">
    <thead>
        <tr>
            <th>
                Name
            </th>
        </tr>
    </thead>
    <tbody data-bind="foreach: Names">
        <tr>
            <td data-bind="text: $data">
            </td>
        </tr>
    </tbody>
</table><!--Contains the page links--><div id="pager"></div>

The Javascript

<script type="text/javascript">
    // Our  ViewModel.
    function pageViewModel() {
        var self = this;
        self.namesGridViewModel = ko.observable(); // contains the viewmodel returned by the WebApi
        self.selectedPageSize = ko.observable(3); // contains the selected page size, default value is 3
        self.availablePageSize = ko.observableArray([1, 2, 3, 4, 5]); // contains the available page sizes a user can select
        self.selectedPage = ko.observable(1); // contains the selected page

        // Add a click event to all future element with a class "pageIndex". This event will fire
        // when the user clicks a specific page.
        $("#pager").on("click", ".pageIndex", function (event) {
            // set the selected page in the viewModel
            self.selectedPage($(this).text());
        });

        // This function will be used to get the data from our WebApi. The requested page and page size are passed
        // as a parameter. The result will be stored in the namesGridViewModel property. This will cause that the subscribe event
        // for the namesGridViewModel will be fired ==> the page links will be created.
        self.navigate = function () {
            $.get("/api/values?page=" + self.selectedPage() + "&pagesize=" + self.selectedPageSize(), self.namesGridViewModel);
        };

        // Function that will subscribe to all the needed events.
        self.SubscribeToEvents = function () {

            // This event will fire when selectedPageSize is changed.
            self.selectedPageSize.subscribe(function (newValue) {
                self.selectedPage(1);
                self.navigate();
            });

            // This event will be fired when the selectedPage is changed.
            self.selectedPage.subscribe(function (newValue) {
                self.navigate();
            });

            // This event will fire when a new value is defined for the namesGridViewModel.
            // It will create the page links below the grid.
            self.namesGridViewModel.subscribe(function (newValue) {
                var numberOfPages = newValue.NumberOfPages;
                var $pager = $("#pager");
                // clear the pager
                $pager.html("");
                // created the pages the user can click on
                for (var i = 1; i <= numberOfPages; i++) {
                    var link = $('<a class="pageIndex">' + i + '</a>');
                    $pager.append(link);
                }
            }, this);
        };
        
        // This function will be used to kick start everything.
        self.bind = function () {
            self.SubscribeToEvents();
            self.navigate();
            ko.applyBindings(self);
        }
    }
    // Create the viewModel and bind it.
    $(function () { new pageViewModel().bind(); })</script>

The result


image

Summary


You have seen how to create a basic paging grid using Knockout.js.You can easily extend this example to also allow sorting. The solution can be downloaded here.
Read more →

2012-05-16

ASP.NET MVC: Set Focus, ViewModel Style

,

In a recent Asp.Net MVC project i had to set a focus on a specific control, but it wasn’t just a specific control. It was calculate in runtime by some conditions. I didn’t just want to create an extra string property on the viewmodel where i could store the id of the control. Off course this would also work but i wanted something safer than those magic strings.

In one of my previous posts (Where is the ClientID?), i was able to determine the Id that is created by the HtmlHelper to create a textbox, checkbox, …

public static class HtmlHelper
{
public static String GetId<TModel,TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression )
{
return TagBuilder.CreateSanitizedId(ExpressionHelper.GetExpressionText(expression));
}
}


So i created a property called Focus on my ViewModelBase class with the exacte same type,  but for the return type of the function i take Object.

public abstract class ViewModelBase<T>
{
public Expression<Func<T,Object>> Focus { get; set; }
}
 

Then my PersonViewModel inherits from ViewModelBase<T> where T equals the PersonViewModel type. That way i have complete intellisence when i want to set the Focus property.

public class PersonViewModel : ViewModelBase<PersonViewModel>
{
public String Name { get; set; }

public String LastName { get; set; }
}

At the view side, i’ll use the GetId extension method to determine the id off the control i want to set the focus to.  I’ll pas the Focus property as parameter for this extension method. Then i’ll use it’s result in a JQuery selector and invoke the .focus() method.

@model ASP.NET_MVC_Set_Focus_ViewModel_Style.Models.PersonViewModel
@{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
@using (Html.BeginForm())
{
<table>
<
tr>
<
td>
Name
</td>
<
td>
@Html.TextBoxFor(m => m.Name)
</td>
</
tr>
<
tr>
<
td>
Lastname
</td>
<
td>
@Html.TextBoxFor(m => m.LastName)
</td>
</
tr>
</
table>
@Html.HiddenFor(m => m.Focus)
<input type="submit" value="ChangeFocus" />
}
<script type="text/javascript">
$(document).ready(function () {
$("#@Html.GetId(Model.Focus)").focus();
});
</script>

At the Controller side, on the HttpGet method, i’ll set the focus on the Name. On the HttpPost method, i’ll set the focus on LastName. That way you’ll see the difference.

public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var personViewModel = new PersonViewModel();

personViewModel.Focus = m => m.Name;

return View(personViewModel);
}

[HttpPost]
public ActionResult Index(PersonViewModel personViewModel)
{
personViewModel.Focus = m => m.LastName;

return View(personViewModel);
}
}

 


The main advantage is that you don’t have to work with those magic strings. When the property is renamed or removed, i’ll get a compiler error. And your code is cleaner.


This code isn’t rocket science but can be very handy. The solution can be downloaded from here.

Read more →