EzDevInfo.com

asp.net-mvc-2 interview questions

Top asp.net-mvc-2 frequently asked interview questions

How do I use VaryByParam with multiple parameters?

In ASP.NET MVC2 I use OutputCache and the VaryByParam attribute. I got it working fine with a single parameter, but what is the correct syntax when I have several parameters on the method?

[OutputCache(Duration=30, VaryByParam = "customerId"]
public ActionResult Index(int customerId)
{
//I've got this one under control, since it only has one parameter
}

[OutputCache(Duration=30, VaryByParam = "customerId"]
public ActionResult Index(int customerId, int languageId)
{
//What is the correct syntax for VaryByParam now that I have a second parameter?
}

How do I get it to cache the pages using both parameters? Do I enter add the attribute twice? Or write "customerId, languageId" as the value??


Source: (StackOverflow)

Can't run ASP.NET MVC 2 web app on IIS 7.5

I'm trying to run an ASP.NET MVC 2 web application under IIS on Windows 7, but I get a 403.14 error. Here are the steps to reproduce:

  1. Open Visual Studio 2010
  2. Create a new ASP.NET MVC 2 project called MvcApplication1
  3. Shift+F5 to run the app. You should see http://localhost:{random_port}/ and the page will render correctly.
  4. Click on MvcApplication1, and select "Properties". Go to the "Web" section.
  5. Select "Use Local IIS Web server" and create a virtual directory.
  6. Save.
  7. Shift+F5 to run the app. You should see http://localhost/MvcApplication1/ and an IIS error HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory..

It's clear that for whatever reason, ASP.NET routing is not working correctly.

Things I've already thought of and tried:

  • Verified that all IIS features are enabled in "Turn Windows features on or off".
  • Verified that the default website is configured to use .NET 4.0
  • Reassigned ASP.NET v4 scripmaps via aspnet_regiis -i in the v4.0.30319 directory.

Here's the most amazing part - this is on a just-built machine. New copy of Windows 7 x64 Ultimate, clean install of Visual Studio 2010 Premium, no other websites and no other work performed.

Anything else I can try?

Setting Visual Studio to use local IIS web server


Source: (StackOverflow)

Advertisements

Why would multiple simultaneous AJAX calls to the same ASP.NET MVC action cause the browser to block?

A few days back I asked this question:

Why does $.getJSON() block the browser?

I fire six jQuery async ajax requests at the same controller action pretty much all at once. Each request takes 10 seconds to return.

Through debugging and logging requests to the action method I notice that the requests are serialised and never run in parallel. i.e. I see a timeline in my log4net logs like this:

2010-12-13 13:25:06,633 [11164] INFO   - Got:1156
2010-12-13 13:25:16,634 [11164] INFO   - Returning:1156
2010-12-13 13:25:16,770 [7124] INFO   - Got:1426
2010-12-13 13:25:26,772 [7124] INFO   - Returning:1426
2010-12-13 13:25:26,925 [11164] INFO   - Got:1912
2010-12-13 13:25:36,926 [11164] INFO   - Returning:1912
2010-12-13 13:25:37,096 [9812] INFO   - Got:1913
2010-12-13 13:25:47,098 [9812] INFO   - Returning:1913
2010-12-13 13:25:47,283 [7124] INFO   - Got:2002
2010-12-13 13:25:57,285 [7124] INFO   - Returning:2002
2010-12-13 13:25:57,424 [11164] INFO   - Got:1308
2010-12-13 13:26:07,425 [11164] INFO   - Returning:1308

Looking at the network timeline in FireFox I see this:

alt text

Both the log sample above and the Firefox network timeline are for the same set of requests.

Are requests to the same action from the same page serialised? I'm aware of serialised access to the Session object in the same session, but no session data is being touched.

I stripped the client side code down to a single request (the longest running one) but this still blocks the browser, i.e. only when the ajax request completes does the browser respond to any link clicking.

What I also observe here (in Chrome's developer tools) is that upon clicking on a link when a long running ajax request is executing it reports a Failed to load resource error immediately which suggests that the browser has killed (or is attempting to kill and waiting?) the ajax request:

alt text

However the browser still takes an age to redirect to the new page.

Are ajax requests really asynchronous or is this sleight of hand because javascript is actually single threaded?

Are my requests just taking too long for this to work?

The problem occurs in Firefox and IE as well.

I also changed the script to use $.ajax directly and explicitly set async: true.

I'm running this on IIS7.5, both the Windows 2008R2 and Windows 7 flavours do the same thing.

Debug and release builds also behave the same.


Source: (StackOverflow)

ActionLink htmlAttributes

WORKS

<a rel='nofollow' href="@Url.Action("edit", "markets", new { id = 1 })" 
            data-rel="dialog" data-transition="pop" data-icon="gear" class="ui-btn-right">Edit</a>

DOES NOT WORK - WHY?

@Html.ActionLink("Edit", "edit", "markets", new { id = 1 }, new {@class="ui-btn-right", data-icon="gear"})

It seems you can't pass something like data-icon="gear" into htmlAttributes?

Suggestions?


Source: (StackOverflow)

How to concatenate several MvcHtmlString instances

I have some doubts about how to concatenate MvcHtmlString instances because of this information found in MSDN :

MvcHtmlString Class Represents an HTML-encoded string that should not be encoded again

Do I risk that strings are HTML-encoded twice when using code like this:

var label = Html.LabelFor(model => model.Email);
var textbox = Html.TextBoxFor(model => model.Email);
var validation = Html.ValidationMessageFor(model => model.Email);

var result = MvcHtmlString.Create(
  label.ToString() + textbox.ToString() + validation.ToString());

(note: this is supposed to go into an HtmlHelper extension method to reduce code-duplication in views).


Source: (StackOverflow)

"The Id field is required" validation message on Create; Id not set to [Required]

This is happening when I try to create the entity using a Create style action in Asp.Net MVC 2.

The POCO has the following properties:

public int Id {get;set;}

[Required]
public string Message {get; set}

On the creation of the entity, the Id is set automatically, so there is no need for it on the Create action.

The ModelState says that "The Id field is required", but I haven't set that to be so. Is there something automatic going on here?

EDIT - Reason Revealed

The reason for the issue is answered by Brad Wilson via Paul Speranza in one of the comments below where he says (cheers Paul):

You're providing a value for ID, you just didn't know you were. It's in the route data of the default route ("{controller}/{action}/{id}"), and its default value is the empty string, which isn't valid for an int. Use the [Bind] attribute on your action parameter to exclude ID. My default route was: new { controller = "Customer", action = "Edit", id = " " } // Parameter defaults

EDIT - Update Model technique

I actually changed the way I did this again by using TryUpdateModel and the exclude parameter array asscoiated with that.

    [HttpPost]
    public ActionResult Add(Venue collection)
    {
        Venue venue = new Venue();
        if (TryUpdateModel(venue, null, null, new[] { "Id" }))
        {
            _service.Add(venue);
            return RedirectToAction("Index", "Manage");
        }
        return View(collection);
    }

Source: (StackOverflow)

Visual Studio 2010 Publish Web feature not including all DLLs

I have an ASP.NET MVC 2 application.

  • Web project contains a reference to SomeProject
  • SomeProject contains references to ExternalAssembly1 and ExternalAssembly2.
  • SomeProject explicitly calls into ExternalAssembly1, but NOT ExternalAssembly2.
  • ExternalAssembly1 calls into ExternalAssembly2

When I perform a local build everything is cool. All DLLs are included in the bin\debug folder. The problem is that when I use the Publish Web command in Visual Studio 2010, it deploys everything except ExternalAssembly2.

It appears to ignore assemblies that aren't directly used (remember, ExternalAssembly2 is only used by ExternalAssembly1).

Is there any way I can tell Visual Studio 2010 to include ExternalAssembly2?

I can write a dummy method that calls into ExternalAssembly2. This does work, but I really don't want to have dummy code for the sole purpose of causing VS2010 to publish the DLL.


Source: (StackOverflow)

Challenges with selecting values in ListBoxFor

This is my first question, and it is probably a poor one, so please be gentle.

Working on my first ASP.Net MVC2 web app recently, I came across some issues when I needed to select multiple values in a list box. I worked around it with some jQuery, but went ahead and put together some very simple code to demonstrate. I'm using EF for the model, with two entities - Customers and HelpDeskCalls:

Controller:

 public ActionResult Edit(int id)
    {
        Customer currCustomer = ctx.Customers.Include("HelpDeskCalls").Where(c => c.ID == id).FirstOrDefault();
        List<HelpDeskCall> currCustCalls = (ctx.HelpDeskCalls.Where(h => h.CustomerID == id)).ToList();
        List<SelectListItem> currSelectItems = new List<SelectListItem>();
        List<String> selectedValues = new List<string>();
        foreach (HelpDeskCall currCall in currCustCalls)
        {
            bool isSelected = (currCall.ID % 2 == 0) ? true : false;
            //Just select the IDs which are even numbers...
            currSelectItems.Add(new SelectListItem() { Selected = isSelected, Text = currCall.CallTitle, Value = currCall.ID.ToString() });
            //add the selected values into a separate list as well...
            if (isSelected)
            {
                selectedValues.Add(currCall.ID.ToString());
            }
        }
        ViewData["currCalls"] = (IEnumerable<SelectListItem>) currSelectItems;
        ViewData["currSelected"] = (IEnumerable<String>) selectedValues;
        return View("Edit", currCustomer);
    }

View:

<div class="editor-field">
            <%: Html.ListBoxFor(model => model.HelpDeskCalls, new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable) ViewData["currSelected"]), new { size = "12" })%>       
            <%: Html.ListBoxFor(model => model.HelpDeskCalls, ViewData["currCalls"] as IEnumerable<SelectListItem>, new { size = "12"}) %>
            <%: Html.ListBox("Model.HelpDeskCalls", new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable)ViewData["currSelected"]), new { size = "12"}) %>      
            <%: Html.ValidationMessageFor(model => model.HelpDeskCalls) %>
</div>

For this sample, I'm just selecting HelpDeskCall.IDs which are even. I'm trying two different syntaxes for ListBoxFor: One uses an IEnumerable of values for selections, one using an IEnumerable of SelectListItems. By default, when I run this code, no selections are made to either ListBoxFor, but the non-strongly typed ListBox selects correctly.

I read this post on ASP.Net and this thread on SO, but no joy. In fact, if I add the override ToString() to my HelpDeskCall class (as suggested in the ASP.net thread) all values are selected, which isn't right either.

If someone could shed some light on how this should work (and what I'm missing or doing wrong), this then neophyte would be very grateful.

John


Source: (StackOverflow)

DisplayName attribute from Resources?

I have a localized application, and I am wondering if it is possible to have the DisplayName for a certain model property set from a Resource.

I'd like to do something like this:

public class MyModel {
  [Required]
  [DisplayName(Resources.Resources.labelForName)]
  public string name{ get; set; }
}

But I can't to it, as the compiler says: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type" :(

Are there any workarounds? I am outputting labels manually, but I need these for the validator output!


Source: (StackOverflow)

ASP.NET MVC Model vs ViewModel

OK, I have been hearing discussion about "ViewModels" in regards to MS's ASP.NET MVC.

Now, that is intended to be a specific kind of Model, correct? Not a specific kind of View.

To my understanding, it's a kind of Model that has a specific purpose of interacting with the View? Or something like that?

Some clarification would be appreciated.


Source: (StackOverflow)

Get DisplayName Attribute without using LabelFor Helper in asp.net MVC

What is the best way to retrieve the display name attribute for an item in your model? I see a lot of people using the LabelFor helper for everything, but a label isn't appropriate if I just want to list the data out. Is there an easy way just get the Name Attribute if I just want to print it out in, say a paragraph?


Source: (StackOverflow)

mvc: does the favicon.ico also look for a controller?

I get an error:

"The controller for path '/favicon.ico' was not found or does not implement IController"

Then I thought: how does the framework know for which files it has to instantiate a controller, because the same thing is true for script, css and other files?

(never thought of that, but now the favicon is complaining, I was wondering....)

But back to the error, why does that occur?


Source: (StackOverflow)

How to specify an area name in an action link?

I have a shared master page which I am using from 2 different areas in my mvc 2 app. The master page has an action link which currently specifies the controller and action, but of course the link doesn't work if I'm in the wrong area. I see no overload for actionlink that takes an area parameter, is it possible to do?


Source: (StackOverflow)

How to write a simple Html.DropDownListFor()?

In ASP.NET MVC 2, I'd like to write a very simple dropdown list which gives static options. For example I'd like to provide choices between "Red", "Blue", and "Green".


Source: (StackOverflow)

GET and POST to same Controller Action in ASP.NET MVC

I'd like to have a single action respond to both Gets as well as Posts. I tried the following

[HttpGet]
[HttpPost]
public ActionResult SignIn()

That didn't seem to work. Any suggestions ?


Source: (StackOverflow)