Showing posts with label ASP.NET MVC3. Show all posts
Showing posts with label ASP.NET MVC3. Show all posts

Tuesday, 13 November 2012

MVC Routing Pages, Css


CSS Routing

If you want ignore routes for all css

RouteTable.Routes.IgnoreRoute("{resource}.css/{*pathInfo}");

Bare in mind that routing of css will not be accepted.

When you want to route css files you need to modify web.config

add into   system.web following

    <compilation>
    <buildProviders>
    <add extension=".css" type="System.Web.Compilation.PageBuildProvider"/>
    </buildProviders>
   </compilation>

and after you can add routing of CSS files

var themePath = CreateThemePath(themeName);
routes.MapPageRoute("layout.css", "layout.css", string.Format("{0}layout.css", themePath));


  private static string CreateThemePath(string themeName)
        {
            return string.Format("~/Content/themes/{0}/", themeName);
        }


After to display your css you need to help to the file with adding code inside of the file:
<%@ ContentType="text/css" %>

Note if you want to run old aspx pages within your mvc application you need to include following route. I am enclosing existing one that I am using.

routes.IgnoreRoute("{*staticfile}", new { staticfile = @".*\.(aspx|js|gif|png|jpg)(/.*)?" });
routes.RouteExistingFiles = true;


Wednesday, 7 November 2012

MVC Tips


I have been working with MVC projects for a while and one common issue I have is find out how to do something easy. I will be updating this article as I go along and add the issues I have had and my solution to this. This is by no means the best way, but it is used as it works.

DataAnnotations

 

Formating DateTime using Html.Editor

 Displaying formated DateTime
 
I needed to display custom format on date in editor for.
You can use decoration to achieve custom formating of datetime field in your model. 
 
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }

Bare in mind that you need to use
@Html.Editor(model=>model.Date) for this field.

Routing

Custom route with aspx page


I have one aspx page which is used in webforms and my project in mvc. I want to have nice routing in place and do not want to display to the user name of the page.

original page is somethinng like: http://localhost:9999/oldwebsite/SayHelloWorld.aspx
my desired name of the page : http://localhost:9999/SayHelloWorld

To achieve this we can use global.asax with custom route in register routes, into which you need to add your custom route.

routes.MapPageRoute("SayHelloWorld", "SayHelloWorld", "/oldwebsite/SayHelloWorld.aspx");

Friday, 2 November 2012

MVC and Sending email

I have often needed email class that works with my website.

Here I am adding small memory nudge :)
How do you setup your webconfig?
how does website use the SmtpClient ?


Here is your configuration of web.config:

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network" from="name@domain.com">
            <network host="smtp.mail.com" 
                     userName="name@domain.com" 
                     password="blog.dotnetclr.com" port="25"/>
        </smtp>
    </mailSettings>
</system.net>
 
Note: this tag is straight in configuration tag of your web.config


And here is the sample C# code that will use the above configuration settings
 
public void SendBy(string to, string subject, string body)
{
    var mailMessage = new System.Net.Mail.MailMessage();
    mailMessage.To.Add(to);
    mailMessage.Subject = subject;
    mailMessage.Body = body;

    var smtpClient = new SmtpClient();
    smtpClient.EnableSsl = true;
    smtpClient.Send(mailMessage);
}

Saturday, 7 April 2012

Implemeting Remote Validation ASP.NET MVC3

I have finally found some time to look at implementation of Remote Validation in ASP.NET MVC3

Definition of a entity DummyUser

public class DummyUser
    {
        [Required]
        [StringLength(6, ErrorMessage = "User name has to be longer than 6 characters.")]
        public string UserName { getset; }
 
        public string Name { getset; }
 
        public string Surname { getset; }
 
        public string Age { getset; }
    }

In Home controller I have created basic Create function. and the view as is displayed

    /// <summary>
    /// Default controller for remote validation.
    /// </summary>
    public class HomeController : Controller
    {
        /// <summary>
        /// Creates new dummy user.
        /// </summary>
        /// <returns> 
        /// View for creating new dummy user. 
        /// </returns>
        [HttpGet]
        public ActionResult Create()
        {
            return View(new DummyUser());
        }
    }

And generate new view : Create for entity.


Update Global.asax to start on this action as:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default"// Route name
                "{controller}/{action}/{id}"// URL with parameters
                new { controller = "Home"
                      action = "Create"
                      id = UrlParameter.Optional } // Parameter defaults
            );
        }


As next step we have to make sure that web.config has set up remote validation.
Which is done in section of App Settings.

 <appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>


Now we have set up everything to start implementing remote validation.

We will add new attribute to UserName.
The attribute "Remote"  uses the jQuery validation plug-in. Read more about remote attribute
 Where we will define action and controller in order [Remote("Action","Controller")]

  public class DummyUser
    {
        [Required]
        [StringLength(6, ErrorMessage = "User name has to be longer than 6 characters.")]
        [Remote("ValidUserName","HomeValidation")]
        public string UserName { getset; }
 
        public string Name { getset; }
 
        public string Surname { getset; }
 
        public string Age { getset; }
    }



Now we need to Create our validation controller.
The recommendation is to create separate validation controller to separate logic from actions and validation, but it is not a rule and you can put your validation into same controller.
In my case i will be using HomeValidationController for this example

    /// <summary>
    /// Home validation controller with no output cache and disabled storing values.
    /// </summary>
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
    public class HomeValidationController : Controller
    {
        /// <summary>
        /// Valids the name of the user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns>Result validation</returns>
        public JsonResult ValidUserName(string userName)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                // we can allow get because there is no data saving
                return Json(trueJsonRequestBehavior.AllowGet);
            }
 
            return Json(falseJsonRequestBehavior.AllowGet);
        }
    }

Now when you start typing into the user name selection you will see request going to validation controller and hitting action in your controller.



The best part on this validation is that you do not have to modify anything in your view and this will just work. That's what i call magic:)