<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3310691039300466880</id><updated>2026-10-08T08:19:01.298+01:00</updated><category term="ASP.NET"/><category term="ASP.NET MVC"/><category term=".NET"/><category term="Ajax"/><category term="C#"/><category term="JSON"/><category term="Moq"/><category term="SMS"/><category term="jquery"/><title type='text'>Emeka Emego</title><subtitle type='html'>Sharing my thoughts and experience with the world.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://emekaemego.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3310691039300466880/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://emekaemego.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Emeka Emego</name><uri>http://www.blogger.com/profile/10321961889198171666</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>2</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3310691039300466880.post-2803489837355755772</id><published>2010-11-01T00:34:00.002+01:00</published><updated>2010-11-01T00:55:43.345+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Ajax"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="jquery"/><category scheme="http://www.blogger.com/atom/ns#" term="JSON"/><category scheme="http://www.blogger.com/atom/ns#" term="Moq"/><title type='text'>How to return HTML in JSON Response using ASP.NET and jQuery</title><content type='html'>During the development of my recent project (&lt;a href=&quot;http://delighthq.com/&quot;&gt;Delight&lt;/a&gt;), I ran into a challenge that normally I wouldn’t believe will take me any time more than what&#39;s required to code it straight up. &lt;br /&gt;
&lt;br /&gt;
Because of the heavy use of ajax in the application, I wrote a generic jquery function to handle all ajax request triggered by a particular group of controls or elements, it was very useful and a time saver for me. In most cases, the JSON is returned in this format: &lt;br /&gt;
&lt;br /&gt;
{Successful: &quot;true&quot;, Message : &quot;response message&quot;, Data&amp;nbsp; : &quot;object or html&quot;}&lt;br /&gt;
&lt;br /&gt;
The interesting part of this response is the &quot;Data&quot; part, it can be of any type, simple or complex object type or (escaped) html.&lt;br /&gt;
&lt;br /&gt;
What I’m going to show you in this post is how to return html content in json response type. The useful thing about this technique is that you get to write your html once in a partial view, which you can then render using full page or ajax request, you can also use the same ajax request with different unrelated url that return different types. This saves you from writing too many codes for different kind of request and reduces view duplication between server and client side.&lt;br /&gt;
&lt;br /&gt;
To demonstrate the trick I explained above, I will be using a mocking framework (&lt;a href=&quot;http://code.google.com/p/moq/&quot;&gt;Moq&lt;/a&gt;) which you can download &lt;a href=&quot;http://code.google.com/p/moq/&quot;&gt;here&lt;/a&gt; and reference in your project. You will also need the jquery library which you can download &lt;a href=&quot;http://jquery.com/&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;The screenshot&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbhqYonMq3e0Jf6oi4fFlJDSr-_luL4Dkf8DbMVVpSVKrXDssAEN2eR-n9KxOQTndjWVvs8FN_TJ_ifbKB0TjmJNHgpKPK8jIQJpORL27wWRJFCzNRihtPpoeagANG_7yG0bmmEwSdy6Y/s1600/return-html-as-json.jpg&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;147&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbhqYonMq3e0Jf6oi4fFlJDSr-_luL4Dkf8DbMVVpSVKrXDssAEN2eR-n9KxOQTndjWVvs8FN_TJ_ifbKB0TjmJNHgpKPK8jIQJpORL27wWRJFCzNRihtPpoeagANG_7yG0bmmEwSdy6Y/s400/return-html-as-json.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;The working&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Start by create a class and name it “Person”. Add the following code below.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public class Person
    {
        public int PersonId { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string JobTitle { get; set; }

        public string Company { get; set; }

        public string ProfilePic { get; set; }

        public List&amp;lt;Email&amp;gt; Emails { get; set; }

        public List&amp;lt;Phone&amp;gt; Phones { get; set; }

        public List&amp;lt;Address&amp;gt; Addresses { get; set; }
    }

    public class Email
    {
        public string Address { get; set; }

        public string Name { get; set; }
    }

    public class Phone
    {
        public string Number { get; set; }

        public string Name { get; set; }
    }

    public class Address
    {
        public string AddressLine { get; set; }

        public string City { get; set; }

        public string State { get; set; }

        public string Country { get; set; }

        public string Name { get; set; }
    }&lt;/pre&gt;&lt;br /&gt;
Now let’s create a service class for our contacts. Add a new class name it &quot;ContactService&quot; and add the following code&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public class ContactService
    {
        public List&amp;lt;Person&amp;gt; GetContacts()
        {&amp;nbsp;&lt;/pre&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;//Normally we would have called the contacts list from a database, but this will do for&lt;/pre&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;//demonstration purpose. &lt;/pre&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;List&amp;lt;Person&amp;gt; contacts = new List&amp;lt;Person&amp;gt;();

            contacts.Add(new Person
                             {
                                 PersonId = 1,
                                 FirstName = &quot;Emeka&quot;,
                                 LastName = &quot;Emego&quot;,
                                 JobTitle = &quot;Web Developer&quot;,
                                 Company = &quot;SymaCord&quot;,
                                 ProfilePic = &quot;~/content/images/emeka-emego.jpg&quot;,
                                 Emails = new List&amp;lt;Email&amp;gt;
                                              {
                                                  new Email
                                                      {
                                                          Address = &quot;symacord@gmail.com&quot;,
                                                          Name = &quot;Personal&quot;
                                                      },
                                                  new Email {Address = &quot;info@symacord.com&quot;, Name = &quot;Professional&quot;}
                                              },
                                 Phones = new List&amp;lt;Phone&amp;gt;
                                              {
                                                  new Phone {Number = &quot;(234)803 780 8732&quot;, Name = &quot;Mobile&quot;},
                                                  new Phone {Number = &quot;(234)838 333 3333&quot;, Name = &quot;Personal&quot;}
                                              },
                                 Addresses = new List&amp;lt;Address&amp;gt;
                                                 {
                                                     new Address
                                                         {
                                                             Name = &quot;Home&quot;,
                                                             AddressLine = &quot;Plot 123 Nowhere&quot;,
                                                             City = &quot;SomeCity&quot;,
                                                             Country = &quot;Nigeria&quot;,
                                                             State = &quot;Lagos&quot;
                                                         }, 
                                                         new Address {
                                                             Name=&quot;Office&quot;,
                                                             AddressLine = &quot;Second address 273&quot;,
                                                             City = &quot;Ikeja&quot;,
                                                             Country = &quot;Nigeria&quot;,
                                                             State = &quot;Lagos&quot; } }
                             });

            contacts.Add(new Person
                             {
                                 PersonId = 2,
                                 FirstName = &quot;Chris&quot;,
                                 LastName = &quot;Ikani&quot;,
                                 JobTitle = &quot;COO&quot;,
                                 Company = &quot;Santoch Lotto&quot;,
                                 ProfilePic = &quot;~/content/images/no-photo.gif&quot;,
                                 Emails =
                                     new List&amp;lt;Email&amp;gt; {new Email {Address = &quot;info@nowheremail.com&quot;, Name = &quot;Personal&quot;}},
                                 Phones = new List&amp;lt;Phone&amp;gt;
                                              {
                                                  new Phone {Number = &quot;(234)138 333 3333&quot;, Name = &quot;Personal&quot;}
                                              },
                                 Addresses = new List&amp;lt;Address&amp;gt;
                                                 {
                                                     new Address
                                                         {
                                                             Name = &quot;Home&quot;,
                                                             AddressLine = &quot;Plot 123 Some place&quot;,
                                                             City = &quot;City place&quot;,
                                                             Country = &quot;Nigeria&quot;,
                                                             State = &quot;Delta&quot;
                                                         } }
                             });

            contacts.Add(new Person
            {
                PersonId = 3,
                FirstName = &quot;Dave&quot;,
                LastName = &quot;Obiuwevbi&quot;,
                JobTitle = &quot;CEO&quot;,
                Company = &quot;Santoch Lotto&quot;,
                ProfilePic = &quot;~/content/images/no-photo.gif&quot;,
                Emails = new List&amp;lt;Email&amp;gt; { new Email { Address = &quot;info@nowheremail.com&quot;, Name = &quot;Personal&quot; } },
                Phones = new List&amp;lt;Phone&amp;gt;(),
                Addresses = new List&amp;lt;Address&amp;gt;()
            });

            contacts.Add(new Person
            {
                PersonId = 4,
                FirstName = &quot;Tunde&quot;,
                LastName = &quot;Oduyoye&quot;,
                JobTitle = &quot;DGM&quot;,
                Company = &quot;Protea Hotel Leadway&quot;,
                ProfilePic = &quot;~/content/images/no-photo.gif&quot;,
                Emails = new List&amp;lt;Email&amp;gt;(),
                Phones = new List&amp;lt;Phone&amp;gt;(),
                Addresses = new List&amp;lt;Address&amp;gt;()
            });

            contacts.Add(new Person
            {
                PersonId = 5,
                FirstName = &quot;Biodu&quot;,
                LastName = &quot;Bameke&quot;,
                JobTitle = &quot;Building Contractor&quot;,
                Company = &quot;Jobams Group&quot;,
                ProfilePic = &quot;~/content/images/no-photo.gif&quot;,
                Emails = new List&amp;lt;Email&amp;gt;(),
                Phones=new List&amp;lt;Phone&amp;gt;(),
                Addresses= new List&amp;lt;Address&amp;gt;()
            });

            contacts.Add(new Person
            {
                PersonId = 6,
                FirstName = &quot;Isaac&quot;,
                LastName = &quot;Okwu&quot;,
                JobTitle = &quot;President&quot;,
                Company = &quot;Africa Farming Project&quot;,
                ProfilePic = &quot;~/content/images/no-photo.gif&quot;,
                Emails = new List&amp;lt;Email&amp;gt;(),
                Phones = new List&amp;lt;Phone&amp;gt;(),
                Addresses = new List&amp;lt;Address&amp;gt;()
            });

            contacts.Add(new Person
            {
                PersonId = 7,
                FirstName = &quot;Johnson&quot;,
                LastName = &quot;Clark&quot;,
                JobTitle = &quot;Graphic Designer&quot;,
                Company = &quot;Design Vision Inc&quot;,
                ProfilePic = &quot;~/content/images/no-photo.gif&quot;,
                Emails = new List&amp;lt;Email&amp;gt;(),
                Phones = new List&amp;lt;Phone&amp;gt;(),
                Addresses = new List&amp;lt;Address&amp;gt;()
            });

            return contacts.OrderBy(x=&amp;gt;x.FirstName).ToList();
        }

        public Person GetContact(int personId)
        {
            return GetContacts().Where(x =&amp;gt; x.PersonId == personId).FirstOrDefault();
        }
    }&lt;/pre&gt;&lt;br /&gt;
Here is the action method to get the list of contacts.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public ActionResult Contacts()
        {
            List&amp;lt;Person&amp;gt; contacts = _contactService.GetContacts();

            return View(contacts);
        }
&lt;/pre&gt;&lt;br /&gt;
In other to be able to return our view in a json response, we need to mock the request and pass our partial view as the return view. The code below demonstrates that. Add this action method in the same controller as above.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public ActionResult Contact(int id)
        {
            //Get the requested person object
            Person contact = _contactService.GetContact(id);

            try
            {
                var writer = new StringWriter();
                var moqContext = new Mock&amp;lt;HttpContextBase&amp;gt;();
                var response = new Mock&amp;lt;HttpResponseBase&amp;gt;();
                moqContext.Setup(ctx =&amp;gt; ctx.Response).Returns(response.Object);
                response.Setup(res =&amp;gt; res.Output).Returns(writer);

                var requestContext = ControllerContext.HttpContext;
                ControllerContext.HttpContext = moqContext.Object;

                var partialView = PartialView(&quot;PartialPersonDetails&quot;, contact);
                partialView.ExecuteResult(ControllerContext);
                var resultHtml = writer.ToString();

                ControllerContext.HttpContext = requestContext;

                return Json(new {Successful = true, Data = resultHtml},JsonRequestBehavior.AllowGet);

            }catch(Exception ex)
            {
                return Json(new { Successful = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }&lt;/pre&gt;&lt;br /&gt;
Now let’s look into our partial view. Create a partial view and name it &quot;PartialPersonDetails&quot;.&lt;br /&gt;
Add the below code to the view.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: html&quot;&gt;&amp;lt;div style=&quot;background:#F3F3F3; padding:10px; overflow:auto;&quot;&amp;gt;
&amp;lt;img src=&quot;&amp;lt;%=Url.Content(Model.ProfilePic) %&amp;gt;&quot; style=&quot;float:left; border:1px solid #cccccc;&quot; /&amp;gt;

&amp;lt;div style=&quot;margin-left:60px;&quot;&amp;gt;
&amp;lt;b&amp;gt;&amp;lt;%=Model.FirstName+ &quot; &quot;+Model.LastName %&amp;gt;&amp;lt;/b&amp;gt;&amp;lt;br /&amp;gt;
&amp;lt;%=Model.JobTitle %&amp;gt; at &amp;lt;%=Model.Company %&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;div class=&quot;contact-detail&quot;&amp;gt;
&amp;lt;%if (Model.Addresses.Count &amp;gt; 0){%&amp;gt;
&amp;lt;fieldset&amp;gt;
&amp;lt;legend&amp;gt;Address&amp;lt;/legend&amp;gt;

&amp;lt;%foreach (var x in Model.Addresses){%&amp;gt;
&amp;lt;dl&amp;gt;
&amp;lt;dt&amp;gt;&amp;lt;%=x.Name %&amp;gt;&amp;lt;/dt&amp;gt;
&amp;lt;dd&amp;gt;
&amp;lt;%:Html.Encode(x.AddressLine) %&amp;gt; &amp;lt;%:Html.Encode(x.City) %&amp;gt;&amp;lt;br /&amp;gt;
&amp;lt;%=x.State %&amp;gt;, &amp;lt;%=x.Country %&amp;gt;.
&amp;lt;/dd&amp;gt;
&amp;lt;/dl&amp;gt;
&amp;lt;%} %&amp;gt;
&amp;lt;/fieldset&amp;gt;
&amp;lt;%} %&amp;gt;

&amp;lt;%if (Model.Emails.Count &amp;gt; 0)
  {%&amp;gt;
&amp;lt;fieldset&amp;gt;
&amp;lt;legend&amp;gt;Email&amp;lt;/legend&amp;gt;

&amp;lt;% foreach (var x in Model.Emails)
      {%&amp;gt;
&amp;lt;dl&amp;gt;
&amp;lt;dt&amp;gt;&amp;lt;%=x.Name%&amp;gt;&amp;lt;/dt&amp;gt;
&amp;lt;dd&amp;gt;&amp;lt;%:Html.Encode(x.Address)%&amp;gt;
&amp;lt;/dd&amp;gt;
&amp;lt;/dl&amp;gt;
&amp;lt;% }%&amp;gt;
&amp;lt;/fieldset&amp;gt;
&amp;lt;% }%&amp;gt;

&amp;lt;%if (Model.Addresses.Count &amp;gt; 0)
  {%&amp;gt;
&amp;lt;fieldset class=&quot;last&quot;&amp;gt;
&amp;lt;legend&amp;gt;Phone&amp;lt;/legend&amp;gt;

&amp;lt;%
      foreach (var x in Model.Phones)
      {%&amp;gt;
&amp;lt;dl&amp;gt;
&amp;lt;dt&amp;gt;&amp;lt;%=x.Name%&amp;gt;&amp;lt;/dt&amp;gt;
&amp;lt;dd&amp;gt;&amp;lt;%:Html.Encode(x.Number)%&amp;gt;
&amp;lt;/dd&amp;gt;
&amp;lt;/dl&amp;gt;
&amp;lt;%
      }%&amp;gt;
&amp;lt;/fieldset&amp;gt;

&amp;lt;%
  }%&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Now create a new view called &quot;Contacts&quot; for the contacts&#39; action method and add the code below&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: html&quot;&gt;&amp;lt;h1&amp;gt;Contacts&amp;lt;/h1&amp;gt;

&amp;lt;div class=&quot;contact-wrapper&quot;&amp;gt;
&amp;lt;ul class=&quot;contact-list&quot;&amp;gt;
&amp;lt;%foreach(var c in Model) {%&amp;gt;
&amp;lt;li&amp;gt;
&amp;lt;div&amp;gt;
&amp;lt;a href=&quot;&amp;lt;%=Url.Action(&quot;contact&quot;,new{id=c.PersonId}) %&amp;gt;&quot;&amp;gt;&amp;lt;%=c.FirstName + &quot; &quot; + c.LastName%&amp;gt;&amp;lt;/a&amp;gt;
&amp;lt;br /&amp;gt;
&amp;lt;span&amp;gt;&amp;lt;%=c.Company %&amp;gt;&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;/li&amp;gt;
&amp;lt;%} %&amp;gt;
&amp;lt;/ul&amp;gt;

&amp;lt;div id=&quot;details&quot;&amp;gt;

&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;&lt;br /&gt;
Here is the ajax call to get and process the response. Add this to the &quot;Contacts&quot; view.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: javascript&quot;&gt;&amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
    $(document).ready(function() {
        $(&#39;ul.contact-list li a&#39;).click(function() {
        var $this = $(this);
            
            $.ajax({
            url: $this.attr(&quot;href&quot;),
            type: &quot;GET&quot;,
                dataType: &quot;json&quot;,
                error: function(xmlHttpRequest, textStatus, errorThrow) {
                    alert(&quot;Woops! &quot; + textStatus);
                },
                success: function(result) {

                    if (result.Successful) {
                        $(&#39;#details&#39;).html(result.Data);
                    }
                    else {
                        alert(result.Message);
                    }
                }
            });
            return false;
        });
    });
&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Note that you need to download and reference the jquery library. Download jquery library here &lt;a href=&quot;http://jquery.com/&quot;&gt;http://jquery.com/&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
That&#39;s all we need to get things to run properly. Note that I omitted the inclusion of css in this post to keep things in point. However, you can download the source code &lt;a href=&quot;https://sites.google.com/site/emekaemego/files/return-html-in-json-response.zip?attredirects=0&amp;amp;d=1&quot;&gt;here&lt;/a&gt; to see this in action.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Somehow this example failed to work in .NET 3.5, but worked fine in 4.0. I hope you find this post useful.</content><link rel='replies' type='application/atom+xml' href='http://emekaemego.blogspot.com/feeds/2803489837355755772/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://emekaemego.blogspot.com/2010/11/how-to-return-html-in-json-response.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3310691039300466880/posts/default/2803489837355755772'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3310691039300466880/posts/default/2803489837355755772'/><link rel='alternate' type='text/html' href='http://emekaemego.blogspot.com/2010/11/how-to-return-html-in-json-response.html' title='How to return HTML in JSON Response using ASP.NET and jQuery'/><author><name>Emeka Emego</name><uri>http://www.blogger.com/profile/10321961889198171666</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbhqYonMq3e0Jf6oi4fFlJDSr-_luL4Dkf8DbMVVpSVKrXDssAEN2eR-n9KxOQTndjWVvs8FN_TJ_ifbKB0TjmJNHgpKPK8jIQJpORL27wWRJFCzNRihtPpoeagANG_7yG0bmmEwSdy6Y/s72-c/return-html-as-json.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3310691039300466880.post-735045706258430234</id><published>2010-10-29T00:34:00.004+01:00</published><updated>2010-11-01T05:00:49.216+01:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".NET"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="SMS"/><title type='text'>Sending SMS With ASP.NET MVC</title><content type='html'>&lt;span style=&quot;font-size: small;&quot;&gt;&lt;b&gt;Introduction&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
In this post, I will be sharing the experience I had (integrating SMS) during the development of &lt;a href=&quot;http://delighthq.com/&quot;&gt;Delight&lt;/a&gt;. With the rising usage of mobile devices, statistics have shown that SMS is the most effective way to communicate, especially for all type of businesses. Honestly, SMS integration to a website if you ask me I would say is easy if you want to stick to just one provider no matter what the future brings. However, this was not the case for &lt;a href=&quot;http://delighthq.com/&quot;&gt;Delight&lt;/a&gt;, we needed solution that won&#39;t require us to rewrite the entire procedure in case we find a better offer by other SMS gateway providers in the future.&lt;br /&gt;
&lt;br /&gt;
The SMS gateway provider I would be using for this post is SMSLive (&lt;a href=&quot;http://smslive247.com/&quot;&gt;http://smslive247.com&lt;/a&gt;). Before you can use their gateway to send SMS, you must sign-up an account with them and create a sub-account that will be used for sending SMS from your application, the account registration is free.&lt;br /&gt;
&lt;br /&gt;
In other to have a better understand of this tutorial, you need the API documentation (optional for this tutorial) which you can download from their website.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Final view of the application.&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYYVOMDgmmaeB8KogWq4u10ztiv-jlJ8p66MU6Ran9NQUWTLp0L5TutmDL3RGKnZWRI6mw-4q_GK2nd5lXDvBuzZH_chUfvVFUkiUhWycEyT8lxfeo-79tCLQnAdLLRnoPVAPj74pU1jM/s1600/sms-app-screenshot.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;265&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYYVOMDgmmaeB8KogWq4u10ztiv-jlJ8p66MU6Ran9NQUWTLp0L5TutmDL3RGKnZWRI6mw-4q_GK2nd5lXDvBuzZH_chUfvVFUkiUhWycEyT8lxfeo-79tCLQnAdLLRnoPVAPj74pU1jM/s400/sms-app-screenshot.jpg&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Programming the SMS functionality&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Enter the following settings in your web.config AppSettings section.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;add key=&quot;SmsUrl&quot; value=&quot;http://www.smslive247.com/http/index.aspx&quot;/&amp;gt;
&amp;lt;add key=&quot;SmsAccount&quot; value=&quot;YOUR-SMSLIVE-EMAIL-ADDRESS&quot;/&amp;gt;
&amp;lt;add key=&quot;SubAccount&quot; value=&quot;YOUR-SMSLIVE-SUBACCOUNT&quot;/&amp;gt;
&amp;lt;add key=&quot;SubAccountPass&quot; value=&quot;YOUR-SMSLIVE-SUBACCOUNT-PASSWORD&quot;/&amp;gt;&lt;/pre&gt;&lt;br /&gt;
Now we need a way to access those information in the web.config AppSetings section. Create a new class and name it “ConfigService” and enter the codes below.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public class ConfigService
    {
       public ConfigService(){}

        /// &amp;lt;summary&amp;gt;
        /// Get the SMS gateway url
        /// &amp;lt;/summary&amp;gt;
        public string SmsUrl
        {
            get { return getAppSetting(typeof(string), &quot;SmsUrl&quot;).ToString(); }
        }

        /// &amp;lt;summary&amp;gt;
        /// Get teh gateway account to use in sending sms message
        /// &amp;lt;/summary&amp;gt;
        public string SmsAccount
        {
            get { return getAppSetting(typeof(string), &quot;SmsAccount&quot;).ToString(); }
        }

        /// &amp;lt;summary&amp;gt;
        /// Get the sub account to use for the sending of sms
        /// &amp;lt;/summary&amp;gt;
        public string SubAccount
        {
            get { return getAppSetting(typeof(string), &quot;SubAccount&quot;).ToString(); }
        }

        /// &amp;lt;summary&amp;gt;
        /// Get the sub account password for the sms gateway
        /// &amp;lt;/summary&amp;gt;
        public string SubAccountPwd
        {
            get { return getAppSetting(typeof(string), &quot;SubAccountPass&quot;).ToString(); }
        }

        private static object getAppSetting(Type expectedType, string key)
        {
            string value = ConfigurationManager.AppSettings[key]; //.Get(key);

            if (value == null)
            {
                throw new Exception(
                    string.Format(&quot;The config file does not have the key &#39;{0}&#39; defined in the AppSetting section.&quot;, key));
            }

            if (expectedType.Equals(typeof (int)))
            {
                return int.Parse(value);
            }

            if (expectedType.Equals(typeof (string)))
            {
                return value;
            }
            else
                throw new Exception(&quot;Type not supported.&quot;);
        }
    }&lt;/pre&gt;&lt;br /&gt;
Let’s create a model for our SMS so it will be easier for us to validate it if we want to.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public class SMS
    {
        public string Numbers { get; set; }

        public string SenderId { get; set; }

        public string Message { get; set; }
    }
&lt;/pre&gt;&lt;br /&gt;
Remember we are not planning to stick with the current SMS provider for life, at least not when we have a better offer from another provider. This will make our SMS integration a bit lengthy but will pay in the long run.&lt;br /&gt;
&lt;br /&gt;
Create a new class, name &quot;SmsService&quot; and add the following codes.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public class SmsService
    {
        private ConfigService _config;
        private Cache _cache;

        private string sessionId_cahe_key = &quot;SmsSessionId_&quot; + &quot;GetSessionId&quot;;

        public SmsService()
        {
            _config = new ConfigService();
            _cache = HttpContext.Current.Cache;
        }

        //Default method for making request to the SMS gateway. This method is not likely to be changed no matter what 
        //SMS gateway provider you want to use in the future.
        private string makeHttpRequest(string url)
        {
            //Initialize the web request
            var webReq = (HttpWebRequest)WebRequest.Create(url);
            webReq.ContentLength = 0;

            webReq.Method = &quot;POST&quot;;//We&#39;re making a post request. This is the recommended method by the gateway.
            webReq.Timeout = 600000;//Set the timeout for the request

            var webResp = (HttpWebResponse)webReq.GetResponse();

            //Read the response and output it.
            Stream answer = webResp.GetResponseStream();
            StreamReader _answer = new StreamReader(answer);

            string result = _answer.ReadToEnd();

            return result;
        }

        //Instead of providing the subaccount and password in information every request to the SMS gateway, 
        //we use this method to get a session id from the gateway and pass to the service. 
        //This approach is more secure.
        public string Login()
        {
            string result = null;
            //Get the gateway url from the web.config AppSettings section
            string smsUrl = _config.SmsUrl;

            //Form the command for login to send to the gatway. You can download the api documentation 
            //from http://smslive247.com
            string smsCmd = &quot;?cmd=login&amp;amp;owneremail=&quot; + _config.SmsAccount + &quot;&amp;amp;subacct=&quot; + _config.SubAccount +
                            &quot;&amp;amp;subacctpwd=&quot; + _config.SubAccountPwd;

            try
            {
                return result = makeHttpRequest(smsUrl + smsCmd);
            }
            catch (Exception err)
            {
                throw err;
            }
        }

        public string GetSessionId()
        {
            string result = null;//hold the returned message from the request
            bool success = false;//indicate if request is seccessful or not

            //First look for the session id in the cache items, if it does not exist, then trying making a request to the SMS gateway
            //for session id, otherwise get it from the cache
            if (_cache[sessionId_cahe_key] != null)
                result = (string)_cache.Get(sessionId_cahe_key);
            else
            {
                string response = Login();//Call the login method to get the session id from the sms gateway

                string errMsg = null;
                //process and return the response data from the login call in a friendly format
                result = GetResponseMessage(response, out success, out errMsg);

                if (success)//add the session id to the cache if the login request was successful
                {
                    _cache.Add(sessionId_cahe_key, result, null, DateTime.Now.AddHours(2), Cache.NoSlidingExpiration,
                               CacheItemPriority.Normal, null);
                }
            }
            return result;//return the session id
        }

        //Process the response from the sms gateway. By default, the gateway&#39;s response is in format below
        //OK: [RESPONSE-Message] -or- ERR: [ERROR NUMBER]: [ERROR DESCRIPTION]
        public string GetResponseMessage(string response, out bool success, out string errMsg)
        {
            //if the response contains &#39;OK&#39;, then the request was successful
            bool isSuccess = response.Substring(0, response.IndexOf(&quot;:&quot;) + 1).Contains(&quot;OK&quot;);
            //This holds the code returned from the request. Anything other than 0 means error
            string code = null;
            //This variable holds the description of the error message
            string errDesc = null;

            //get the code for the request
            if (isSuccess)
            {
                code = response.Substring(response.IndexOf(&quot;:&quot;) + 2);
            }
            else
            {
                code = response.Substring(response.IndexOf(&quot;:&quot;) + 2, response.LastIndexOf(&quot;:&quot;) - 1);
                errDesc = response.Substring(response.LastIndexOf(&quot;:&quot;) + 2);
            }

            success = isSuccess;
            errMsg = errDesc;
            return code;
        }

        public string Send(SMS sms)
        {
            string sessionId = GetSessionId(); //Get the session id
            string smsUrl = _config.SmsUrl; //Get the sms gatway url from the config file

            //Form the command for sending message. You can download the API documentation for full list of commands
            //from http://smslive247.com
            string smsCmd = String.Format(&quot;?cmd=sendmsg&amp;amp;sessionid={0}&amp;amp;message={1}&amp;amp;sender={2}&quot; +
                                          &quot;&amp;amp;sendto={3}&amp;amp;msgtype=0&quot;, sessionId, sms.Message, sms.SenderId, sms.Numbers);

            bool isSuccess = false;
            string errMsg = null;
            //Send sms message
            string response = makeHttpRequest(smsUrl + smsCmd);

            //Process the response from the gateway
            string code = GetResponseMessage(response, out isSuccess, out errMsg);

            //401 error code indicate invalid Session ID. If the session id is not valid, then delete it from cache and make a 
            //request to get a new session id from the sms gateway
            if (code == &quot;401&quot;)
            {
                _cache.Remove(sessionId_cahe_key);//delete the session id from the cache

                sessionId = GetSessionId(); //Get the session id
                smsCmd = String.Format(&quot;?cmd=sendmsg&amp;amp;sessionid={0}&amp;amp;message={1}&amp;amp;sender={2}&quot; +
                                          &quot;&amp;amp;sendto={3}&amp;amp;msgtype=0&quot;, sessionId, sms.Message, sms.SenderId, sms.Numbers);

                return makeHttpRequest(smsUrl + smsCmd);//resend the sms to the gateway
            }

            return response;
        }
    }
&lt;/pre&gt;&lt;br /&gt;
I would be using ASP.NET MVC in the following example, the process to implement this in whatever C# application you want to use it in is the same. If you are working on ASP.NET web-form for example, all you need to do is just substitute the Action method to the control’s method you want to trigger the sending of SMS from.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;[HttpPost, ActionName(&quot;send-sms&quot;)]
        public ActionResult SendSMS(SMS sms)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    bool isSuccess = false;
                    string errMsg = null;
                    string response = _smsService.Send(sms); //Send sms

                    string code = _smsService.GetResponseMessage(response, out isSuccess, out errMsg);

                    if (!isSuccess)
                    {
                        ModelState.AddModelError(&quot;&quot;, errMsg);
                    }
                    else
                    {
                        ViewData[&quot;SuccessMsg&quot;] = &quot;Message was successfully sent.&quot;;
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(&quot;&quot;, ex.Message);
                }
            }

            return View(sms);
        }
&lt;/pre&gt;&lt;br /&gt;
The HTML&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: html&quot;&gt;&amp;lt;%=Html.ValidationSummary() %&amp;gt;
&amp;lt;%if (ViewData[&quot;SuccessMsg&quot;]!=null){%&amp;gt;
&amp;lt;div class=&quot;success&quot;&amp;gt;&amp;lt;%=ViewData[&quot;SuccessMsg&quot;] %&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;%} %&amp;gt;

&amp;lt;form action=&quot;&amp;lt;%=Url.Action(&quot;send-sms&quot;,&quot;home&quot;) %&amp;gt;&quot; method=&quot;post&quot;&amp;gt;
&amp;lt;label for=&quot;Numbers&quot;&amp;gt;Send To&amp;lt;/label&amp;gt;&amp;lt;br /&amp;gt;
&amp;lt;%=Html.TextBox(&quot;Numbers&quot;) %&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

&amp;lt;label for=&quot;Message&quot;&amp;gt;Message&amp;lt;/label&amp;gt;&amp;lt;br /&amp;gt;
&amp;lt;%=Html.TextArea(&quot;Message&quot;,&quot;&quot;,new{rows=&quot;4&quot;,cols=&quot;35&quot;}) %&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

&amp;lt;label for=&quot;SenderId&quot;&amp;gt;SenderId&amp;lt;/label&amp;gt;&amp;lt;br /&amp;gt;
&amp;lt;%=Html.TextBox(&quot;SenderId&quot;) %&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

&amp;lt;input type=&quot;submit&quot; value=&quot;Send Now&quot; /&amp;gt;
&amp;lt;/form&amp;gt;&lt;/pre&gt;&lt;br /&gt;
That’s it, we now have a functional website with SMS functionality. You can download the full source code &lt;a href=&quot;https://sites.google.com/site/emekaemego/files/send-sms-with-asp.net-mvc.zip?attredirects=0&amp;amp;d=1&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Conclusion&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
I hope you find this useful. Depending on the kind of Application you’re building, there’s so much more you can do with SMS to make things easier for your users.</content><link rel='replies' type='application/atom+xml' href='http://emekaemego.blogspot.com/feeds/735045706258430234/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://emekaemego.blogspot.com/2010/10/sending-sms-with-aspnet-mvc.html#comment-form' title='207 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3310691039300466880/posts/default/735045706258430234'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3310691039300466880/posts/default/735045706258430234'/><link rel='alternate' type='text/html' href='http://emekaemego.blogspot.com/2010/10/sending-sms-with-aspnet-mvc.html' title='Sending SMS With ASP.NET MVC'/><author><name>Emeka Emego</name><uri>http://www.blogger.com/profile/10321961889198171666</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYYVOMDgmmaeB8KogWq4u10ztiv-jlJ8p66MU6Ran9NQUWTLp0L5TutmDL3RGKnZWRI6mw-4q_GK2nd5lXDvBuzZH_chUfvVFUkiUhWycEyT8lxfeo-79tCLQnAdLLRnoPVAPj74pU1jM/s72-c/sms-app-screenshot.jpg" height="72" width="72"/><thr:total>207</thr:total></entry></feed>