Pages

AJAX with MVC3

Suppose you have a page which requires you to load content inline in response to some action.  In the below example, you have a filter and a “preview” button which needs to show some sample data.



You could have the button do a post and have the MVC handler parse the form fields and render the view with the data you want to show.  But, you may have a complex page with many tabs and want to optimize form performance.    In such a case, you want to send just the form data for the current tab and inject the response into the current page.  Here is how to do that:
Here is the HTML of the relevant section of the “Export” tab:
<fieldset id="previewFld" title="Preview Results">        
 
<div class="btn green preview">
<a href="#">Preview</a></div>
<div class="clear"></div>
 
<span id="preview">&nbsp;</span>    
</fieldset>
 
<div class="btn orange submit">
<a href="#">Export to CSV</a></div>
<div class="clear"></div>
Note the two href’s with attributes of btn.  Here is the relevant JavaScript:
$(document).ready(function () {
 
    $('.preview').click(function () {
        $('#preview').html('<strong>Loading...</strong>');
        $.post('Home/Preview/?' + $(this).closest("form").serialize(), function (data) {
            $('#preview').html(data);
        });
    });
 
    $('.submit').click(function () {
        $('.submit a').html("Loading...");
        $(this).closest("form").submit();
        return false;
    });
 
});
The “Export” button submits the entire form.  The “Preview” button on the other hand:
  1. Shows the “loading” text.
  2. Serializes the content of the parent form
  3. Posts the serialized content to a url
  4. Renders the response from that URL in the designated div
Here is Preview.cshtml:
@{
    Layout =null;
}
@model  Models.ExportFilter
 
<h2>@ViewBag.Message</h2>
 
<strong>Name, Source, Email, DateAdded</strong>
<ul>
    @foreach (var item in Model.MarketingList)
    {
	<li>@item.FirstName, @item.Source, @item.Email, @item.DateAdded.ToShortDateString()</li>
    }&nbsp;
</ul>&nbsp;
Note that I am overriding the default Layout because I don’t want to show the normal header/footer. _Blank.cshtml contains solely “@RenderBody()”
The handler for the /Preview target is:
[HttpPost]
        public ActionResult Preview(ExportFilter filter)
        {
            var export = new EmailExporter(filter);
            List emailList = export.Process();
            ViewBag.Message = string.Format("{0:##,#} records to be exported", emailList.Count); 
            return View(filter); 
        }
Now when I click “preview”, I get a momentary “loading” screen and then the rendered view.

Dependency Injection With Asp.Net MVC3

What dependency injection means is that instead of writing code like this in your controller
private IBlogService _BlogService;
public BlogController()
{
    _BlogService = new BlogService();
}
you write code like this
private IBlogService _BlogService;
public BlogController(IBlogService blogService)
{
    _BlogService = blogService;
}
the benefits of dependency injection are your classes are not tightly coupled, are more testable, and really is pluggable.
To enable dependency injection into your controllers in ASP.NET MVC2 you had to create a new class derived from DefaultControllerFactory and override the GetControllerInstance method to create the controller using your dependency injection container e.g.
public class IoCControllerFactory : DefaultControllerFactory
{

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return (IController)_container.GetInstance(controllerType);
    }
}
and then you had to register this controller factory as the default in the Application_Start event in the global.ascx file
protected void Application_Start()
{

    ControllerBuilder.Current.SetControllerFactory(typeof(IoCControllerFactory));
    ...
}
The problem here is that you need to create a separate custom class for the model binders, and for custom model metadata.
ASP.NET MVC 3 makes things easier to inject dependencies by introducing a new interface IDependencyResolver. The benefit here is that this DependencyResolver is responsible to resolve dependencies not only for the controller but also for the services (repository, logger etc.) consumed by the controller, view engine, view binders, and the model and model metadata.
The interface has two methods
object GetService(Type serviceType);
IEnumerable<object> GetServices(Type serviceType);
which return either a single object or a list of object of serviceType. If a type cannot be resolved by the dependency resolver then ASP.NET MVC3 expects the resolver to return null.
If the dependency resolver returns null then ASP.NET MVC3 will fall back to the default factory class to instantiate the interface object.
To use this new interface simply create a new class which implements this interface
public class UnityDependencyResolver : IDependencyResolver
{
    private IUnityContainer _contianer;
    UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }

    #region IDependencyResolver Members
    public object GetService(Type serviceType)
    {
        try
        {
            return _container.GetInstance(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.GetAllInstances(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }
    #endregion
}
I’m using Unity as my dependency container and since Unity throws a ResolutionFailedException exception if it cannot resolve a  type we need to wrap it in a try/catch block and return null in case of exception.
Just like the controller factory we need to register our dependency resolver at Application_Start event in our global.ascx
protected void Application_Start()
{
    var container = new UnityContainer()
        .LoadConfiguration();

    DependencyResolver.SetResolver(container);
    ...
}
You can either configure your container at runtime or via the .config file. I prefer the .config approach because then I can easily take my application to any environment (DEv vs QA) and switch out my EmailLogger with NullLogger or as required by changing the mapping in the .config file.

Thanks

Compare Date Jquery Validation In MVC3



Add "endDate" and "startDate" To Your Textbox class .


<script type="text/javascript">
    $(document).ready(function () {
        $.validator.addMethod("endDate", function (value, element) {
            var startDate = $('.startDate').val();
            return Date.parse(startDate) <= Date.parse(value);
        }, "* End date must be after start date");
     
     
        $('#myform').validate();
    });

</script>