MVC3 – Passing dynamic objects to views

In this post, I’ll explain how to pass a model with dynamic objects to a view.

If you are new to C# 4 features like dynamic objects, ExpandoObject etc I suggest to visit below links to get familliar with the concepts.

http://msdn.microsoft.com/en-us/library/dd264741.aspx

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

By using dynamic and ExpandoObject, you can pass a runtime object with some dynamic properties to a view and use them efficiently.

Controller Action
——————
——————

 public ActionResult DisplayDynamic()
{
      dynamic obj = new ExpandoObject();
      obj.FirstName = "Raj";
      obj.LastName = "Bandi";
      obj.Country = "Australia";

      return View("DynamicView", obj);
}

DynamicView.cshtml
————————
————————
//here I’m creating a simple view without any layout just to explain how to use the object

@model dynamic

  1. First Name: @Model.FirstName
  2. Last Name: @Model.LastName
  3. Country: @Model.Country

Demo
————–
—————
http://demos.rajbandi.net/mvc3/home/dynamic

Source Code
————-
————–

http://code.rajbandi.net/examples/mvc3/mvc3source.zip

MVC3 Posting form data without refreshing a page

In this post, I’ll explain how to post form data without refreshing a page using JQuery ajax and JSON.

Here, I assume a model is used to render form(form elements names same as model properties).

**Step 1:**

Define an action that takes Model as parameter and returns a json object along with attribute HttpPost(simple way)

[HttpPost]
public JsonResult PostMethod(YourModelType m)
{
   // Do something with the model, all the form elements posted are available in the model

   //return json string. Json method that serializes any C# object to json format.
   return Json(your object, JsonRequestBehavior.AllowGet);
}

**Step 2:**

Add javascript function to post data

function PostData(form)
{
  //use only if you wish to validate the form before posting, requires JQuery.validate plugin
 if (!$(form).valid()) {

        return;
    }

    // use $.post, $.ajax can also be used but with some additional parameters
    // 1st parameter is form action to submit, 2nd parameter serialized form data
    // 3rd parameter is the function to be called after successful post and return value
    $.post($(form).attr('action'), $(form).serialize(), function (data) {

           alert('Posted successfully and received data...'+data);


    });
}

Call PostData function to post data on any element action i,e. click etc.

Sharepoint 2010 Dialogs

In Sharepoint, SP.UI script namespace provides required methods and classes for showing different types of dialogs.

The following are the list of various dialog methods available under class ModalDialog

1) showModalDialog: To show a modal dialog with some options.

SP.UI.ModalDialog.showModalDialog(options);

2) ShowPopupDialog :

To show a modal dialog with an url and without any options.

3) showWaitScreenSize : this one is used to show a wait screen dialog with a close button

SP.UI.ModalDialog.showWaitScreenSize(title,message,callback,height,width);

for more information on options visit http://msdn.microsoft.com/en-us/library/ff411803.aspx

4) showWaitScreenWithNoClose:

To show a wait screen without any cancel button.

SP.UI.ModalDialog.showWaitScreenWithNoClose(title,message,height,width);

5) commonModalDialogOpen(url,options,callback,args)

To show a modal dialog with url, options, callback, parameters.

SP.UI.ModalDialog.commonModalDialogOpen(url, options, callback, parameters);

ModalDialog class provides other non dialog methods

1) RefreshPage:

SP.UI.ModalDialog.RefreshPage(dialogResult);

2) close:
To close a dialog.
SP.UI.ModalDialog.close(dialogResult);

for showModalDialog and commonModalDialog, there are two ways to pass the options

//generic way

var options = { title: ‘Dialog1’ .height: 300 ,width:300
,url : ‘http://www.rajbandi.net’
}

//with DialogOptions class

var options = SP.UI.$create_DialogOptions();
options.title = ‘Dialog1’;
options.height = 300;
options.width=300;
options.url = ‘http://www.rajbandi.net’;

You can also display html string instead of url but have to do in indirect way. Options html property takes a DOM element as an input. When html and url properties are provided, url takes precedence.

var div = document.createElement('div');
div.innerHTML = 'Dialog html demo Dialog html takes an DOM object but not an html string';
var options = {    title: 'Dialog1',
width : 300
,height:300
,html = div
}

To refresh a page after dialog ok clicked.

Sharepoint 2010 Registering script files in a WebPart

Sharepoint 2010 provides a custom tag ScriptLink to register script files in a webpart. This can also be done using simple html script tag but using ScriptLink ensures all the sharepoint script namespaces are available for your custom script.

All the scripts that are to be registered should be placed in Layouts/ProjectName folder of your project. By default, when you create a project Layouts folder will not be added.

To add it, right click on your project –> add –> SharePoint “Layouts” Mapped Folder

A default folder with project name will be automatically created under Layouts folder.

Add your custom script files in Layouts/ProjectName/Scripts folder (create Scripts folder if not exist, it can be any name like JS etc.).

Add your code in the script file, here in this example I have added some alert code which is opened by clicking on web part button ‘click here’

Now add ScriptLink tag in your visual web part (i,e. .ascx control)
If you want to do the same in a standard web part, add the below code in OnPreRender method

ScriptLink.register(page,”RajWebPartsDemo/Scripts/RajDemoScript.js”, false);

Deploy your solution and add a your webpart in a page (say home page).

On clicking button ‘Click Here’ an alert is displayed.

Rendering Bing search with JSRender using API

JSRender is a jscript template engine very much similar to JQuery templates. It is replacing JQuery templates in the near future and still in beta. The main advantage of any template engine is to reduce the jscript code for rendering dhtml with some data. JSRender can be used with or without using JQuery.

Please visit below link to know more about JSRender

[http://borismoore.github.com/jsrender/demos/index.html](http://borismoore.github.com/jsrender/demos/index.html)

Here, in this example, I will try to explain how you can use Bing Search API to render a search interface with JSRender.

Bing Search API exposes http endpoints that can provide results in XML or JSON. Please visit below link for more information on Bing Search API

[http://www.bing.com/developers/s/APIBasics.html](http://www.bing.com/developers/s/APIBasics.html)

Bing API URL format

**Json**

http://api.bing.net/json.aspx?parameters

**XML**

http://api.bing.net/xml.aspx?parameters

Bing Search API request consists of following required and optional parameters

**Required**

1) AppID : Your site application key provided by Bing.

2) Query: Search text

3) Sources: Web or Images etc..

Optional

1) Web.Offset: Offset 0 means first page

2) Web.Count: Total number of records to be fetched.

>Please note that in order to hide my APPID and misuse, I have installed an application on my server to reverse proxy bing api. What I mean is in the example code there is no direct api calling to bing website but it has to go through my site.

http://bing.rajbandi.net/search/json.aspx

or

http://bing.rajbandi.net/search/xml.aspx

All the api requests initiated to my site doesn’t require any APIID but Query and sources parameters are required.

Demo
———-
———

[http://demos.rajbandi.net/bing/search/jsrender.html](http://demos.rajbandi.net/bing/search/jsrender.html)

Source
————
————

Access source at JSFiddle.net
[http://jsfiddle.net/rajbandi/7XNbS/](http://jsfiddle.net/rajbandi/7XNbS/)