tags:

views:

74

answers:

2

I'm building an MVC app for the first time. Currently, my app presents a small form that will let the user provide an input string (a url) and on submit, will use the user's input to create a new record within the db table, and output a clean url. I'd like to add a condition within my homecontroller file that will:

1) check if the "url" input already exists within the database table and 2) if so, will display that record verses creating a duplicate record.

    Index View --------------------

        <%@ 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"&gt;

        <html xmlns="http://www.w3.org/1999/xhtml" >
        <head runat="server">
            <title></title>
        </head>
        <body>
            <div>
            <form action="/Home/Create" method="post">
            Enter:  <input type="text" name="urlToShorten" id="shortenUrlInput" />
            <input type="submit" value="Shorten" />
            </form>

            </div>



        </body>
        </html>

    Create View ------------------------------------------------------------

    <%@ 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"&gt;

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title></title>
    </head>
    <body>
        <div>
        The clean url:<br />
        <%= string.Format("{0}/{1}",Request.Url.GetLeftPart(UriPartial.Authority),ViewData["shortUrl"]) %>

        </div>
    </body>
    </html>

    Homecontroller----------------------------------------------------------


        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Mvc;
        using System.Web.Mvc.Ajax;
        using ShortUrl.Models;

        namespace ShortUrl.Controllers
        {
            [HandleError]
            public class HomeController : Controller
            {
                public ActionResult Index()
                {
                    return View();

                }

                [HandleError]
                public ActionResult Create(string urlToShorten)
                {
                    if (string.IsNullOrEmpty(urlToShorten)) 

                    {

                        return RedirectToAction("Index");
                    }



                    else
                    {
                        long result = ShortUrlFunctions.InsertUrl(urlToShorten);
                        ViewData["shortUrl"] = result;
                        return View("Create");
                    }
                }
                [HandleError]
                public ActionResult Resolve(long? id)
                {
                    if (!id.HasValue || id.Value == 0)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        string url = ShortUrlFunctions.RetrieveUrl(id.Value);
                        if (url == null)
                        {
                            return RedirectToAction("Index");
                        }
                        else
                        {

                            return Redirect(url);
                        }
                    }
                }
            }
        }

------------ShortUrlFunctions.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ShortUrl.Models
{
   public static class ShortUrlFunctions
   {
       public static string RetrieveUrl(long inputKey)
       {
           using (ShortUrlEntities db = new ShortUrlEntities())
           {


                   var existingUrl = (from t in db.ShortURLSet where
t.id == inputKey select t).Take(1);
                   if (existingUrl.Count() == 1)
                   {
                       return existingUrl.First().url;

                   }
                   else
                   {
                       return null;
                   }
           }
       }

           public static  long InsertUrl(string inputUrl)
           {
               long result = 0;
               if(!string.IsNullOrEmpty(inputUrl))
               {
                   using (ShortUrlEntities db = new ShortUrlEntities())
                   {
                       if (inputUrl.IndexOf(@"://") == -1) inputUrl =
"http://" + inputUrl;
                           ShortURL su = new ShortURL();
                       su.url = inputUrl;
                       db.AddToShortURLSet(su);
                       db.SaveChanges();
                       result = su.id;

           }
       }

               return result;


    }
  }
 }
A: 

You will need to add [AcceptVerbs(HttpVerbs.Post)] to the Create method you wish to accept the form post.

Hope that helps,

Dan

Daniel Elliott
He won't NEED that attribute since that attribute is used to LIMIT the handling to POST only. On the other hand, yes, it would be nice if he put that attribute since he is only accepting POST requests.
paracycle
Indeed, good point, well made ;)
Daniel Elliott
A: 

What you need is a method on your ShortUrlFunctions class that can check if a given url exists in your database. If that method is named GetIdForUrl then all you need to do is change your Create action as follows:

        [HandleError]
        public ActionResult Create(string urlToShorten)
        {
            if (string.IsNullOrEmpty(urlToShorten)) 
            {
                return RedirectToAction("Index");
            }

            // No need for an else here since you have a return on the if above.

            long result = ShortUrlFunctions.GetIdForUrl(urlToShorten);


            // I am assuming that the function above returns 0 if url is not found.            
            if (result == 0)
            {
                result = ShortUrlFunctions.InsertUrl(urlToShorten);
            }

            ViewData["shortUrl"] = result;
            return View("Create");
        }

EDIT: (In response to your comment)

A sample implementation of GetIdForUrl would be:

public static long GetIdForUrl(string inputUrl) 
{
    using (ShortUrlEntities db = new ShortUrlEntities())
    {
        var checkUrl = (from t in db.ShortURLSet 
                        where t.url == inputUrl select t.id);

        if (checkUrl.Count() == 1) 
        {
            return checkUrl.First();
        }
        else
        {
            return 0;
        }
    }
}
paracycle
thanks for your response. should my function look something like this?public static long GetIdForUrl(string inputUrl){using (ShortUrlEntities db = new ShortUrlEntities()){var checkUrl = (from t in db.ShortURLSet where t.url== inputUrl select t).Take(1);if (checkUrl.Count() == 1){ return checkUrl.id;
MG
The end of your comment is cropped, but from what I gather that would work. However, note that you don't need the ".Take(1)" after the query; you can check for ".Count() == 1" without that "Take". Also I cannot see the end but I assume you return 0 if no records are found.
paracycle
Expanded the answer in response to your comment.
paracycle
wow, it worked perfectly!!! Thank you so much.
MG
Glad it worked. Have fun coding.
paracycle