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

Wednesday, October 23, 2013

What are Validation Annotations?

Data annotations are attributes you can find in System.ComponentModel.DataAnnotations namespace. These attributes provide server-side validation, and the framework also supports client-side validation when you use one of the attributes on a model property. You can use four attributes in the DataAnnotations namespace to cover common validation scenarios,
Required, String Length, Regular Expression, Range.

http://www.codeproject.com/Articles/639717/MVC-Interview-Questions-and-Answers-All-about-MVC

What are Scaffold templates?

These templates use the Visual Studio T4 templating system to generate a view based on the model type selected. Scaffolding in ASP.NET MVC can generate the boilerplate code we need for create, read, update, and delete (CRUD) functionality in an application. The scaffolding templates can examine the type definition for, and then generate a controller and the controller’s associated views. The scaffolding knows how to name controllers, how to name views, what code needs to go in each component, and where to place all these pieces in the project for the application to work.

What namespaces MVC use and for what?

What is namespace of ASP.NET MVC?

ASP.NET MVC namespaces as well as classes are located in assembly System.Web.Mvc.
Note: Some of the content has been taken from various books/articles.

What is System.Web.Mvc namespace?

This namespace contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.

What is System.Web.Mvc.Ajax namespace?

System.Web.Mvc.Ajax namespace contains classes that supports Ajax scripting in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings as well.

What is System.Web.Mvc.Async namespace?

System.Web.Mvc.Async namespace contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application.

What is System.Web.Mvc.Html namespace?

System.Web.Mvc.Html namespace contains classes that help render HTML controls in an MVC application. This namespace includes classes that support forms, input controls, links, partial views, and validation.

http://www.codeproject.com/Articles/639717/MVC-Interview-Questions-and-Answers-All-about-MVC

What are the various types of Application Templates used to create an MVC application?

The various templates are as follows:
  1. The Internet Application template: This contains the beginnings of an MVC web application — enough so that you can run the application immediately after creating it and see a few pages. This template also includes some basic account management functions which run against the ASP.NET Membership.
  2. The Intranet Application template: The Intranet Application template was added as part of the ASP.NET MVC 3 Tools Update. It is similar to the Internet Application template, but the account management functions run against Windows accounts rather than the ASP.NET Membership system.
  3. The Basic template: This template is pretty minimal. It still has the basic folders, CSS, and MVC application infrastructure in place, but no more. Running an application created using the Empty template just gives you an error message. Why use Basic template? The Basic template is intended for experienced MVC developers who want to set up and configure things exactly how they want them.
  4. The Empty template: The Basic template used to be called the Empty template, but developers complained that it wasn’t quite empty enough. With MVC 4, the previous Empty template was renamed Basic, and the new Empty template is about as empty as we can get. It has the assemblies and basic folder structure in place, but that’s about it.
  5. The Mobile Application template: The Mobile Application template is preconfigured with jQuery Mobile to jump-start creating a mobile only website. It includes mobile visual themes, a touch-optimized UI, and support for Ajax navigation.
  6. The Web API template: ASP.NET Web API is a framework for creating HTTP services. The Web API template is similar to the Internet Application template but is streamlined for Web API development. For instance, there is no user account management functionality, as Web API account management is often significantly different from standard MVC account management. Web API functionality is also available in the other MVC project templates, and even in non-MVC project types.

What is Dependency Resolution?

What is Dependency Resolution?

MVC 3 introduced a new concept called a dependency resolver, which greatly simplified the use of dependency injection in your applications. This made it easier to decouple application components, making them more configurable and easier to test.
Support was added for the following scenarios:
  • Controllers (registering and injecting controller factories, injecting controllers)
  • Views (registering and injecting view engines, injecting dependencies into view pages)
  • Action filters (locating and injecting filters)
  • Model binders (registering and injecting)
  • Model validation providers (registering and injecting)
  • Model metadata providers (registering and injecting)
  • Value providers (registering and injecting)

What is JSON Binding?

What is JSON Binding?

MVC 3 included JavaScript Object Notation (JSON) binding support via the new JsonValueProviderFactory, enabling the action methods to accept and model-bind data in JSON format. This is especially useful in advanced Ajax scenarios like client templates and data binding that need to post data back to the server.

What is the “page lifecycle” of an ASP.NET MVC?

Following processes are performed by ASP.NET MVC page:

  1. App initialization
  2. Routing
  3. Instantiate and execute controller
  4. Locate and invoke controller action
  5. Instantiate and render view

Main features of MVC2, MVC3 and MVC4

ASP.NET MVC 2 was released in March 2010. Its main features are:

  • Introduction of UI helpers with automatic scaffolding with customizable templates
  • Attribute-based model validation on both client and server
  • Strongly typed HTML helpers
  • Improved Visual Studio tooling
  • There were also lots of API enhancements and “pro” features, based on feedback from developers building a variety of applications on ASP.NET MVC 1, such as:
    • Support for partitioning large applications into areas
    • Asynchronous controllers support
    • Support for rendering subsections of a page/site using Html.RenderAction
    • Lots of new helper functions, utilities, and API enhancements

ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011. Some of the top features in MVC 3 included:

  • The Razor view engine
  • Support for .NET 4 Data Annotations
  • Improved model validation
  • Greater control and flexibility with support for dependency resolution and global action filters
  • Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
  • Use of NuGet to deliver software and manage dependencies throughout the platform

Following are the top features of MVC4:

  • ASP.NET Web API
  • Enhancements to default project templates
  • Mobile project template using jQuery Mobile
  • Display Modes
  • Task support for Asynchronous Controllers
  • Bundling and minification

Different return types of a controller action methods

The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.

1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

What are the advantages of ASP.NET MVC?

Below are the advantages of ASP.NET MVC-

1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

ViewBag vs ViewData in MVC


ASP.NET MVC offers us three options ViewData and VieBag for passing data from controller to view and in next request. ViewData and ViewBag are almost similar.

Similarities between ViewBag & ViewData :
 1.Helps to maintain data when you move from controller to view.
 2.Used to pass data from controller to corresponding view.
 3.Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:
 1.ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
 2.ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
 3.ViewData requires typecasting for complex data type and check for null values to avoid error.
 4.ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:
public ActionResult Index()
{
    ViewBag.Name = "Pratap Singh";
    return View();
}

public ActionResult Index()
{
    ViewData["Name"] = "Pratap Singh";
    return View();
}


 In View:

@ViewBag.Name
@ViewData["Name"]

Monday, May 14, 2012

Using jQuery and JSON Action methods in MVC

  1. jQuery + JSON Action Methods = Cool
    It is easy to return a JSON object instead of a view.
    public JsonResult Create(string CategoryName)
    {
        var category = new Models.Category();
        category.Name = CategoryName;
        category.URLName = CategoryName.ToLower().Replace(" ", "-");
        categoryRepository.Add(category);
        categoryRepository.Save();
    
        return Json(category);
    }
    <script class="str" type="<span">
    "text/javascript" language="javascript">
        $("#CreateNewCategory").click(function() {
            $.getJSON("/category/create/",
                      { "CategoryName": $("#NewCategoryName").val() },
                      CategoryAdded);
                  });
    
                  function CategoryAdded(category) {
                      $("#CategoryList").append("
    
  2. + category.URLName + "/cat\">" + category.Name + "
  3. "
    ); } </script>

Sunday, May 13, 2012

What is Repository Pattern in ASP.NET MVC?

What is Repository Pattern in ASP.NET MVC?
Repository pattern is usefult for decoupling entity operations form presentation, which allows easy mocking and unit testing.
“The Repository will delegate to the appropriate infrastructure services to get the job done. Encapsulating in the mechanisms of storage, retrieval and query is the most basic feature of a Repository implementation”
“Most common queries should also be hard coded to the Repositories as methods.”
Which MVC.NET to implement repository pattern Controller would have 2 constructors on parameterless for framework to call, and the second one which takes repository as an input:
class myController: Controller
{
    private IMyRepository repository;
 
    // overloaded constructor
    public myController(IMyRepository repository)
    {
        this.repository = repository;
    }
 
    // default constructor for framework to call
    public myController()
    {
        //concreate implementation
        myController(new someRepository());
    }
...
 
    public ActionResult Load()
    {
        // loading data from repository
        var myData = repository.Load();
    }
}

What is difference between Viewbag and Viewdata in ASP.NET MVC?

What is difference between Viewbag and Viewdata in ASP.NET MVC?

The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

How to access Viewstate values of this page in the next page?

How to access Viewstate values of this page in the next page?

PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page.
Page poster = this.PreviousPage;
Once that is done, a control can be found from the previous page and its state can be read.
Label posterLabel = poster.findControl("myLabel");
 string lbl = posterLabel.Text;

How to call javascript function on the change of Dropdown List in ASP.NET MVC?

How to call javascript function on the change of Dropdown List in ASP.NET MVC?
Create a java-script function:
Call the function:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Products, "Value", "Text"),
"Please Select a product", new { id = "dropDown1",
onchange="selectedIndexChanged()" })%>

What is the ‘page lifecycle’ of an ASP.NET MVC?

What is the ‘page lifecycle’ of an ASP.NET MVC?
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

Friday, May 11, 2012

Remove MVC Action from Cache

For removing the Cache from the action so it get refresh each time, use the below stuff
 
public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted ( ActionExecutedContext context )
    {
        context.HttpContext.Response.Cache.SetCacheability( HttpCacheability.NoCache );
    }
}

[HttpGet]
[NoCache]
public JsonResult GetSomeStuff ()
{
    ...
}