Archive for the ‘ASP.NET MVC2’ Category
Using Google Maps API to mark multiple addresses fetched from database ASP.NET MVC2 and Geocoder
This tutorial will cover marking multiple addresses stored in database on Google Maps. For example this can be useful for marking chain of shops or restaurants or others.
The idea is to get something like this:

Before starting it we have to obtain a key for using their API.
You can do it here:
http://code.google.com/apis/maps/signup.html
Generate your key and save it
1. Create new Empty MVC2 project
2. Insert new .ashx file call it Maps.ashx.
I placed mine the folder Services which I created before.

3. Insert this code
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Maps : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
string sXml = createMarkers();
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Write(sXml);
}
public bool IsReusable {
get { return true; }
}
private string createMarkers() {
// Create the xml document container
XmlDocument doc = new XmlDocument();//
Create the XML Declaration, and append it to XML document
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("markers");
doc.AppendChild(root);
// Here you can create a loop and fetching data from database like
/* while(rdr.Read()) {
XmlElement marker = doc.CreateElement("marker");
marker.SetAttribute("name", rdr["name"].ToString());
marker.SetAttribute("address", rdr["address"].ToString());
root.AppendChild(marker);
}
*/
// To retrieve data using a C# go here:
// http://www.akadia.com/services/dotnet_data_reader.html
// We will enter it manually
XmlElement marker = doc.CreateElement("marker");
marker.SetAttribute("name", "L'arruzz");
marker.SetAttribute("address", "C/ PORTUGAL, 35, 03003 ALICANTE");
root.AppendChild(marker);
XmlElement marker2 = doc.CreateElement("marker");
marker2.SetAttribute("name", "CERVECERIA VICTOR");
marker2.SetAttribute("address", "C/ SAN AGATÁNGELO, 37, 03007 ALICANTE");
root.AppendChild(marker2);
return doc.OuterXml;
}
}
4. Next step is to create HomeController and create Index View.
public ActionResult Index()
{ return View();
}
5. Now run your project and check if xml is being genrated by go to url of ashx file:
http://localhost:your_port_number/Services/Maps.ashx
For example in my case:http://localhost:1951/Services/Maps.ashx

6. Go back your HomeController and right click and create Index View. Your code should be the same as below:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=here_we_enter_google_api_key" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
function load() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
geocoder = new GClientGeocoder();
// Here enter your url of ashx file
GDownloadUrl("http://localhost:1951/Services/Maps.ashx", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
showAddress(address,name);
}
});
}
}
function showAddress(address, name) {
if (geocoder) {
geocoder.getLatLng(
name+","+address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 13);
var marker = createMarker(point, name, address);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name, address) {
var marker = new GMarker(point);
var html = "<b>" + name + "</b> <br/>" + address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div>
<div id="map" style="width: 1000px; height: 600px"></div>
</div>
</body>
</html>
Run it and there we go!

You can also do it without ashx and return xml as an ActionResult
public ActionResult PrintMarkers() {
XmlDocument doc = new XmlDocument();//
Create the XML Declaration, and append it to XML document
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("markers");
doc.AppendChild(root);
XmlElement marker = doc.CreateElement("marker");
marker.SetAttribute("name", "L'arruzz");
marker.SetAttribute("address", "C/ PORTUGAL, 35, 03003 ALICANTE");
root.AppendChild(marker);
XmlElement marker2 = doc.CreateElement("marker");
marker2.SetAttribute("name", "CERVECERIA VICTOR");
marker2.SetAttribute("address", "C/ SAN AGATÁNGELO, 37, 03007 ALICANTE");
root.AppendChild(marker2);
return doc.OuterXml;
}
And simply call it from script of JavaScript:
GDownloadUrl("http://localhost:1951/Home/PrintMarkers/", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
showAddress(address,name);
}
});
Will do the same.
Good luck!
ASP.NET MVC2 jQuery Form Post Tutorial
Here is a little tutorial that I wrote about posting form using jQuery and Form plugin.I’m using Visual Studio 2008.
If you want to see how to post form with JSON check my other post:
http://arturito.net/2011/01/25/asp-net-mvc2-jquery-form-post-with-json-tutorial/
1. Open Visual Studio
2. Create MVC2 Empty Web Application

3. Right click Controllers in Solution Explorer and select Add Controller
4. Name it HomeController

5. Right Click on Models in Solution Explorer and select Add Class…
6. Name it RegisterViewModel

Insert this piece of code:
namespace MVC2JQuery.Models
{
public class RegisterViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
7. In the Toolbar click Build->Build Solution
8. Go back to HomeController and right click on Index() and select Add View …
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index() // <-- right click here
{
return View();
}
}

9. You will be taken to your Index.aspx
10. Now run the application by hitting F5 (Click ok on “Debugging Not Enabled” with option “Modify…”)
11. Now, let’s make it do something. Stop Debugging and go back to Home Controller and add Action:
[HttpPost]
public ActionResult Index(RegisterViewModel data)
{
// here you can save data to database
// and return some feedback to the user
return Content("You submitted: " + data.FirstName + " " + data.LastName);
}
12. Your HomeController will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC2JQuery.Models;
namespace MVC2JQuery.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(RegisterViewModel data)
{
// here you can save data to database
// and return some feedback to the user
return Content("You submitted: " + data.FirstName + " " + data.LastName);
}
}
}
Build project and Run it.


13. Now go to Scripts in Solution Explorer and remove all file that are in there. We won’t be using them.
14. Download:
jQuery:
http://code.jquery.com/jquery-1.4.4.min.js
jQuery Form Plugin:
https://github.com/malsup/form/raw/master/jquery.form.js
Save them in Scripts folder of your project.


15. Go to Views and chaage Index.aspx as below:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<mvc2JQuery.Models.RegisterViewModel>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
<script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery-1.4.4.min.js")%>"></script>
<script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery.form.js")%>"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#result-user', // id of the div where we are going to display result
beforeSubmit: showRequest,
success: showResponse,
type: 'post',
resetForm: true
};
$('#form-user').ajaxForm(options); // id of the form we wish to submit
});
function showRequest(formData, jqForm, options) {
$("#result-user").empty().html('Loading....');
$("#form-user :input").attr("disabled", true); // disable all form inputs while loading
}
function showResponse(responseText, statusText, xhr, $form) {
$("#result-user").empty().html(responseText);
$("#form-user :input").attr("disabled", false);
}
</script>
</head>
<body>
<% using (Html.BeginForm("Index","Home",FormMethod.Post, new { id="form-user", name="form-user"})) {%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.FirstName) %>
<%= Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.LastName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.LastName) %>
<%= Html.ValidationMessageFor(model => model.LastName) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div id="result-user"></div>
</body>
</html>
16. Let’s go back to our HomeController and amend Index action:
[HttpPost]
public ActionResult Index(RegisterViewModel data)
{
// here you can save data to database
// and return some feedback to the user
if(Request.IsAjaxRequest())
return Content("You submitted: " + data.FirstName + " " + data.LastName + " using jQuery");
else
return Content("You submitted: " + data.FirstName + " " + data.LastName);
}
17. Build and Run


Here you can download working example
Note: If you are not getting the same result make sure that:
1.Ids are equal
$(‘#form-user‘).ajaxForm(options);
Html.BeginForm(“Index”,”Home”,FormMethod.Post, new { id=”form-user“, name=”form-user“})
$(“#result-user“).empty().html(responseText);
File and Image Upload with ASP.NET MVC2 with CKEditor WYSIWYG – Rich Text Editor
This tutorial is for CKeditor not FCKeditor.
1. Download it an extract CKeditor
http://ckeditor.com/download
2. Extract it to /Scripts/wysiwyg
3. Create MVC2 project
4. In
<script type="text/javascript" src="<%= Url.Content("~/Scripts/wysiwyg/ckeditor.js")%>"></script>
5. View will look like this:
<!-- Indicate which textarea to be converted to WYSISWG editor --> ...
<div> <%= Html.LabelFor(model => model.Description) %></div>
<div><%= Html.TextAreaFor(model => model.Description, new { @class = "ckeditor" })%>
<%= Html.ValidationMessageFor(model => model.Description) %>
</div>
<!-- Indicate which action is responsible for image upload -->
<script type="text/javascript">
CKEDITOR.replace('Description', {
filebrowserImageUploadUrl: '/UploadImage'
});
</script>
...
6. Controller will look like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadImage(HttpPostedFileBase upload,string CKEditorFuncNum, string CKEditor, string langCode) {
string url; // url to return
string message; // message to display (optional)
// here logic to upload image
// and get file path of the image
// path of the image
string path = "Content/Images/my_uploaded_image.jpg";
// will create http://localhost:1457/Content/Images/my_uploaded_image.jpg
url = Request.Url.GetLeftPart(UriPartial.Authority) +"/"+ path;
// passing message success/failure
message = "Image was saved correctly";
// since it is an ajax request it requires this string
string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction("+CKEditorFuncNum+", \""+url+"\", \""+message+"\");</script></body></html>";
return Content(output); }