EzDevInfo.com

asp.net-mvc interview questions

Top asp.net-mvc frequently asked interview questions

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

In ASP.NET MVC, what is the difference between:

  • Html.Partial and Html.RenderPartial
  • Html.Action and Html.RenderAction

Source: (StackOverflow)

A potentially dangerous Request.Form value was detected from the client

Every time a user posts something containing < or > in a page in my web application, I get this exception thrown.

I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.

Trapping the exception and showing An error has occured please go back and re-type your entire form again, but this time please do not use < doesn't seem professional enough to me.

Disabling post validation (validateRequest="false") will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.

Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded. So the .Text property of my text-box will be something & lt; html & gt;

Is there a way I can do this from a handler?


Source: (StackOverflow)

Advertisements

Can an ASP.NET MVC controller return an Image?

Can I create a Controller that simply returns an image asset?

I would like to route this logic through a controller, whenever a URL such as the following is requested:

www.mywebsite.com/resource/image/topbanner

The controller will look up topbanner.png and send that image directly back to the client.

I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.

Is this possible?


Source: (StackOverflow)

Writing/outputting HTML strings unescaped

I've got safe/sanitized HTML saved in a DB table.

How can I have this HTML content written out in a Razor view?

It always escapes characters like < and ampersands to &amp;.


Source: (StackOverflow)

File Upload ASP.NET MVC 3.0

I want to upload file in . How can I upload the file using html input file control?


Source: (StackOverflow)

Can you overload controller methods in ASP.NET MVC?

I'm curious to see if you can overload controller methods in ASP.NET MVC. Whenever I try, I get the error below. The two methods accept different arguments. Is this something that cannot be done?

The current request for action 'MyMethod' on controller type 'MyController' is ambiguous between the following action methods:


Source: (StackOverflow)

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

I am configuring an MVC 3 project to work on a local install of IIS and came across the following 500 error:

Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list.

It turns out that this is because ASP.Net was not completely installed with IIS even though I checked that box in the "Add Feature" dialog. To fix this, I simply ran the following command at the command prompt

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

If I had been on a 32 bit system, it would have looked like the following:

%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i

My question is, is there a way to install IIS on a windows 7 box to use .NET 4.0 (MVC 3) without taking this extra step?


Source: (StackOverflow)

NUnit vs Visual Studio 2008's Test Projects for Unit Testing? [closed]

I am going to be starting up a new project at work and want to get into unit testing. We will be using VS 2008, C#, and the ASP.NET MVC stuff. I am looking at using either NUnit or the built in test projects that VS2008 has, but I am open to researching other suggestions. Is one system better than the other or perhaps easier to use/understand than the other? I am looking to get this project set up as kind of the "best practice" for our development efforts going forward.

Thanks for any help and suggestions!!


Source: (StackOverflow)

ASP.NET MVC controller actions that return JSON or partial html

I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?


Source: (StackOverflow)

What is new in asp.net mvc 5 [closed]

Today on twitter I saw a tutorial for ASP.NET MVC 5. I didn't know it existed.

So, what are the new, cool features of MVC 5? What are the biggest differences compared to MVC 4?


Source: (StackOverflow)

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

I want to save my Edit to Database and I am using Entity FrameWork Code-First in ASP.NET MVC 3 / C# but I am getting errors. In my Event class, I have DateTime and TimeSpan datatypes but in my database, I've got Date and time respectively. Could this be the reason? How can I cast to the appropriate datatype in the code before saving changes to database.

public class Event
{
    public int EventId { get; set; }
    public int CategoryId { get; set; }
    public int PlaceId { get; set; }
    public string Title { get; set; }
    public decimal Price { get; set; }
    public DateTime EventDate { get; set; }
    public TimeSpan StartTime { get; set; }
    public TimeSpan EndTime { get; set; }
    public string Description { get; set; }
    public string EventPlaceUrl { get; set; }
    public Category Category { get; set; }
    public Place Place { get; set; }
}

Method in the controller >>>> Problem at storeDB.SaveChanges();

// POST: /EventManager/Edit/386        
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    var theEvent = storeDB.Events.Find(id);

    if (TryUpdateModel(theEvent))
    {
        storeDB.SaveChanges();
        return RedirectToAction("Index");
    }
    else
    {
        ViewBag.Categories = storeDB.Categories.OrderBy(g => g.Name).ToList();
        ViewBag.Places = storeDB.Places.OrderBy(a => a.Name).ToList();
        return View(theEvent);
    }
}

with

public class EventCalendarEntities : DbContext
{
    public DbSet<Event> Events { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Place> Places { get; set; } 
}

SQL Server 2008 R2 Database / T-SQL

EventDate (Datatype = date)  
StartTime (Datatype = time)  
EndTime (Datatype = time)  

Http Form

EventDate (Datatype = DateTime) e.g. 4/8/2011 12:00:00 AM  
StartTime (Datatype = Timespan/time not sure) e.g. 08:30:00  
EndTime (Datatype = Timespan/time not sure) e.g. 09:00:00  

Server Error in '/' Application.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Source Error:

Line 75:             if (TryUpdateModel(theEvent))
Line 76:             {
Line 77:                 storeDB.SaveChanges();
Line 78:                 return RedirectToAction("Index");
Line 79:             }

Source File: C:\sep\MvcEventCalendar\MvcEventCalendar\Controllers\EventManagerController.cs Line: 77

Stack Trace:

[DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.]


Source: (StackOverflow)

ASP.NET MVC 3 - Partial vs Display Template vs Editor Template

So, the title should speak for itself.

To create re-usable components in ASP.NET MVC, we have 3 options (could be others i haven't mentioned):

Partial View:

@Html.Partial(Model.Foo, "SomePartial")

Custom Editor Template:

@Html.EditorFor(model => model.Foo)

Custom Display Template:

@Html.DisplayFor(model => model.Foo)

In terms of the actual View/HTML, all three implementations are identical:

@model WebApplications.Models.FooObject

<!-- Bunch of HTML -->

So, my question is - when/how do you decide which one of the three to use?

What i'm really looking for is a list of questions to ask yourself before creating one, for which the answers can be used to decide on which template to use.

Here's the 2 things i have found better with EditorFor/DisplayFor:

  1. They respect model hierarchies when rendering HTML helpers (e.g if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName").

  2. More robust, e.g if you had a List<T> of something in your ViewModel, you could use @Html.DisplayFor(model => model.CollectionOfFoo), and MVC is smart enough to see it's a collection and render out the single display for each item (as opposed to a Partial, which would require an explicit for loop).

I've also heard DisplayFor renders a "read-only" template, but i don't understand that - couldn't i throw a form on there?

Can someone tell me some other reasons? Is there a list/article somewhere comparing the three?


Source: (StackOverflow)

Using Razor within JavaScript

Is it possible or is there a workaround to use Razor syntax within JavaScript that is in a view (cshtml)?

I am trying to add markers to a Google map... For example, I tried this, but I'm getting a ton of compilation errors:

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.

    // Now add markers
    @foreach (var item in Model) {

        var markerlatLng = new google.maps.LatLng(@(Model.Latitude), @(Model.Longitude));
        var title = '@(Model.Title)';
        var description = '@(Model.Description)';
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }
</script>

Source: (StackOverflow)

Render a view as a string

I'm wanting to output two different views (one as a string that will be sent as an email), and the other the page displayed to a user.

Is this possible in ASP.NET MVC beta?

I've tried multiple examples:

RenderPartial to String in ASP.NET MVC Beta
If I use this example, I receive the "Cannot redirect after HTTP headers have been sent.".

MVC Framework: Capturing the output of a view
If I use this, I seem to be unable to do a redirectToAction, as it tries to render a view that may not exist. If I do return the view, it is completely messed up and doesn't look right at all.

Does anyone have any ideas/solutions to these issues i have, or have any suggestions for better ones?

Many thanks!

Below is an example. What I'm trying to do is create the GetViewForEmail method:

public ActionResult OrderResult(string ref)
{
  //Get the order
  Order order = OrderService.GetOrder(ref);

  //The email helper would do the meat and veg by getting the view as a string
  //Pass the control name (OrderResultEmail) and the model (order)
  string emailView = GetViewForEmail("OrderResultEmail", order);

  //Email the order out
  EmailHelper(order, emailView);
  return View("OrderResult", order);
}

Accepted answer from Tim Scott (changed and formatted a little by me):

public virtual string RenderViewToString(
  ControllerContext controllerContext,
  string viewPath,
  string masterPath,
  ViewDataDictionary viewData,
  TempDataDictionary tempData)
{
  Stream filter = null;
  ViewPage viewPage = new ViewPage();

  //Right, create our view
  viewPage.ViewContext = new ViewContext(controllerContext, new WebFormView(viewPath, masterPath), viewData, tempData);

  //Get the response context, flush it and get the response filter.
  var response = viewPage.ViewContext.HttpContext.Response;
  response.Flush();
  var oldFilter = response.Filter;

  try
  {
      //Put a new filter into the response
      filter = new MemoryStream();
      response.Filter = filter;

      //Now render the view into the memorystream and flush the response
      viewPage.ViewContext.View.Render(viewPage.ViewContext, viewPage.ViewContext.HttpContext.Response.Output);
      response.Flush();

      //Now read the rendered view.
      filter.Position = 0;
      var reader = new StreamReader(filter, response.ContentEncoding);
      return reader.ReadToEnd();
  }
  finally
  {
      //Clean up.
      if (filter != null)
      {
        filter.Dispose();
      }

      //Now replace the response filter
      response.Filter = oldFilter;
  }
}

Example usage

Assuming a call from the controller to get the order confirmation email, passing the Site.Master location.

string myString = RenderViewToString(this.ControllerContext, "~/Views/Order/OrderResultEmail.aspx", "~/Views/Shared/Site.Master", this.ViewData, this.TempData);

Source: (StackOverflow)

How can I properly handle 404 in ASP.NET MVC?

I am just getting started on ASP.NET MVC so bear with me. I've searched around this site and various others and have seen a few implementations of this.

EDIT: I forgot to mention I am using RC2

Using URL Routing:

routes.MapRoute(
    "Error",
     "{*url}",
     new { controller = "Errors", action = "NotFound" }  // 404s
);

The above seems to take care of requests like this (assuming default route tables setup by initial MVC project): "/blah/blah/blah/blah"

Overriding HandleUnknownAction() in the controller itself:

// 404s - handle here (bad action requested
protected override void HandleUnknownAction(string actionName) {
    ViewData["actionName"] = actionName;
    View("NotFound").ExecuteResult(this.ControllerContext);
}  

However the previous strategies do not handle a request to a Bad/Unknown controller. For example, I do not have a "/IDoNotExist", if I request this I get the generic 404 page from the web server and not my 404 if I use routing + override.

So finally, my question is: Is there any way to catch this type of request using a route or something else in the MVC framework itself?

OR should I just default to using Web.Config customErrors as my 404 handler and forget all this? I assume if I go with customErrors I'll have to store the generic 404 page outside of /Views due to the Web.Config restrictions on direct access. Anyway any best practices or guidance is appreciated.


Source: (StackOverflow)