EzDevInfo.com

asp.net-mvc-3 interview questions

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

What is the @Html.DisplayFor syntax for?

I understand that in Razor, @Html does a bunch of neat things, like generate HTML for links, inputs, etc.

But I don't get the DisplayFor function...

Why would I write:

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

when I could just write:

@Model.Title

Source: (StackOverflow)

How to use ternary operator in razor (specifically on HTML attributes)?

With the WebForms view engine, I'll commonly use the ternary operator for very simple conditionals, especially within HTML attributes. For example:

<a class="<%=User.Identity.IsAuthenticated ? "auth" : "anon" %>">My link here</a>

The above code will give the <a> tag a class of auth or anon depending on whether the user is authenticated.

What is the equivalent syntax with the Razor view engine? Because Razor requires HTML tags to "know" when to jump in and out of code and markup, I'm currently stuck with the following:

@if(User.Identity.IsAuthenticated)  { <a class="auth">My link here</a> }
else { <a class="anon">My link here</a> }

This is, to put it mildly, terrible.

I would love to do something like this, but am struggling to understand how in Razor:

<a class="@=User.Identity.IsAuthenticated ? "auth" : "anon";">My link here</a>

--

Update:

In the meantime, I've created this HtmlHelper:

public static MvcHtmlString Conditional(this HtmlHelper html, Boolean condition, String ifTrue, String ifFalse)
{
  return MvcHtmlString.Create(condition ? ifTrue : ifFalse);
}

which can be called like this from Razor:

<a class="@Html.Conditional(User.Identity.IsAuthenticated, "auth", "anon")">My link here</a>

Still, I am hoping there's a way to use the ternary operator without falling back to wrapping it in an extension method.


Source: (StackOverflow)

Advertisements

Entity Framework 5 Updating a Record

I have been exploring different methods of editing/updating a record within Entity Framework 5 in an ASP.NET MVC3 environment, but so far none of them tick all of the boxes I need. I'll explain why.

I have found three methods to which I'll mention the pros and cons:

Method 1 - Load original record, update each property

var original = db.Users.Find(updatedUser.UserId);

if (original != null)
{
    original.BusinessEntityId = updatedUser.BusinessEntityId;
    original.Email = updatedUser.Email;
    original.EmployeeId = updatedUser.EmployeeId;
    original.Forename = updatedUser.Forename;
    original.Surname = updatedUser.Surname;
    original.Telephone = updatedUser.Telephone;
    original.Title = updatedUser.Title;
    original.Fax = updatedUser.Fax;
    original.ASPNetUserId = updatedUser.ASPNetUserId;
    db.SaveChanges();
}    

Pros

  • Can specify which properties change
  • Views don't need to contain every property

Cons

  • 2 x queries on database to load original then update it

Method 2 - Load original record, set changed values

var original = db.Users.Find(updatedUser.UserId);

if (original != null)
{
    db.Entry(original).CurrentValues.SetValues(updatedUser);
    db.SaveChanges();
}

Pros

  • Only modified properties are sent to database

Cons

  • Views need to contain every property
  • 2 x queries on database to load original then update it

Method 3 - Attach updated record and set state to EntityState.Modified

db.Users.Attach(updatedUser);
db.Entry(updatedUser).State = EntityState.Modified;
db.SaveChanges();

Pros

  • 1 x query on database to update

Cons

  • Can't specify which properties change
  • Views must contain every property

Question

My question to you guys; is there a clean way that I can achieve this set of goals?

  • Can specify which properties change
  • Views don't need to contain every property (such as password!)
  • 1 x query on database to update

I understand this is quite a minor thing to point out but I may be missing a simple solution to this. If not method one will prevail ;-)


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)

There is already an open DataReader associated with this Command which must be closed first

I have this query and I get the error in this function:

var accounts =
    from account in context.Accounts
    from guranteer in account.Gurantors

 select new AccountsReport
    {
        CreditRegistryId = account.CreditRegistryId,
        AccountNumber = account.AccountNo,
        DateOpened = account.DateOpened,
    };

 return accounts.AsEnumerable()
                   .Select((account, index) => new AccountsReport()
                           {
                               RecordNumber = FormattedRowNumber(account, index + 1),
                               CreditRegistryId = account.CreditRegistryId,
                                  DateLastUpdated = DateLastUpdated(account.CreditRegistryId, account.AccountNumber),
                               AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)}).OrderBy(c=>c.FormattedRecordNumber).ThenByDescending(c => c.StateChangeDate);


 public DateTime DateLastUpdated(long creditorRegistryId, string accountNo)
        {
            var dateReported = (from h in context.AccountHistory
                                where h.CreditorRegistryId == creditorRegistryId && h.AccountNo == accountNo
                                select h.LastUpdated).Max();
            return dateReported;
        }

Error is:

There is already an open DataReader associated with this Command which must be closed first.

[EDIT]

stack trace added:

InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
   System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +5008639
   System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +23
   System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +144
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +87
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +443

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +479
   System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +683
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +119
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +38
   System.Linq.Enumerable.Single(IEnumerable`1 source) +114
   System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3(IEnumerable`1 sequence) +4
   System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +29
   System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +91
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +69
   System.Linq.Queryable.Max(IQueryable`1 source) +216
   CreditRegistry.Repositories.CreditRegistryRepository.DateLastUpdated(Int64 creditorRegistryId, String accountNo) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1497
   CreditRegistry.Repositories.CreditRegistryRepository.<AccountDetails>b__88(AccountsReport account, Int32 index) in D:\Freelance Work\SuperExpert\CreditRegistry\CreditRegistry\Repositories\CreditRegistryRepository.cs:1250
   System.Linq.<SelectIterator>d__7`2.MoveNext() +198
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.<GetEnumerator>d__0.MoveNext() +96

Source: (StackOverflow)

What's the difference between ViewData and ViewBag?

I saw the ViewBag in MVC 3. How's that different than ViewData in MVC 2?


Source: (StackOverflow)

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Is there a tutorial or code example of using Ajax.BeginForm within Asp.net MVC 3 where unobtrusive validation and Ajax exist?

This is an elusive topic for MVC 3, and I cannot seem to get my form to work properly. It will do an Ajax submit but ignores the validation errors.


Source: (StackOverflow)

Why is JsonRequestBehavior needed?

Why is Json Request Behavior needed?

If I want to restrict the HttpGet requests to my action I can decorate the action with the [HttpPost] attribute

Example:

[HttpPost]
public JsonResult Foo()
{
    return Json("Secrets");
}

// Instead of:
public JsonResult Foo()
{
    return Json("Secrets", JsonRequestBehavior.AllowGet);
}

Why isn't [HttpPost]sufficient?
Why the framework "bugs" us with the JsonRequestBehavior.AllowGet for every JsonResult that we have. If I want to deny get requests I'll add the HttpPost attribute.


Source: (StackOverflow)

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

I would like to have 2 separate Layouts in my application. Let say one is for the Public section of the website and the other is for the Member side.

For simplicity lets say all the logic for each of theses sites is wrapped neatly into 2 distinct controllers.

  • PublicController
  • StaffController

And that they each have a corresponding Layout for all the View under each.

  • _PublicLayout.cshtml
  • _StaffLayout.cshtml

How do I use the _ViewStart.cshtml file to specify that all View's / Action under "Public" use the PublicLayout and everything under "Staff" use the StaffLayout?

Thanks!


Source: (StackOverflow)

Multiple types were found that match the controller named 'Home'

I currently have two unrelated MVC3 projects hosted online.

One works fine, the other doesn't work, giving me the error:

Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request.

If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

The way my hoster works is that he gives me FTP access and in that folder I have two other folder, one for each of my applications.

ftpFolderA2/foo.com

ftpFolderA2/bar.com

foo.com works fine, I publish my application to my local file system then FTP the contents and it works.

When I upload and try to run bar.com, the issue above fires and prevents me from using my site. All while foo.com still works.

Is bar.com searching from controllers EVERYWHERE inside of ftpFolderA2 and that's why it's finding another HomeController? How can I tell it to only look in the Controller folder as it should?

Facts:

  1. Not using areas. These are two COMPLETELY unrelated projects. I place each published project into each respective folder. Nothing fancy.
  2. Each project only has 1 HomeController.

Can someone confirm this is the problem?


Source: (StackOverflow)

Multiple models in a view

I have want to have 2 models in a view. The page contains both LoginViewModel and RegisterViewModel.

e.g.

public class LoginViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

Do I need to make another view which holds these 2 views?

public BigViewModel
{
    public LoginViewModel LoginViewModel{get; set;}
    public RegisterViewModel RegisterViewModel {get; set;}
}

I need the validation attributes to be brought forward to the view, this is why I need the ViewModels.

Isn't there another way such as (without the BigViewModel):

 @model ViewModel.RegisterViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Name)
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

 @model ViewModel.LoginViewModel
 @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
 {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
 }

Source: (StackOverflow)

Returning a file to View/Download in ASP.NET MVC

I'm encountering a problem sending files stored in a database back to the user in ASP.NET MVC. What I want is a view listing two links, one to view the file and let the mimetype sent to the browser determine how it should be handled, and the other to force a download.

If I choose to view a file called SomeRandomFile.bak and the browser doesn't have an associated program to open files of this type, then I have no problem with it defaulting to the download behavior. However, if I choose to view a file called SomeRandomFile.pdf or SomeRandomFile.jpg I want the file to simply open. But I also want to keep a download link off to the side so that I can force a download prompt regardless of the file type. Does this make sense?

I have tried FileStreamResult and it works for most files, it's constructor doesn't accept a filename by default, so unknown files are assigned the a file name based on the url (which does not know the extension to give based on content type). If I force the file name by specifying it, I lose the ability for the browser to open the file directly and I get a download prompt. Has anyone else encountered this.

These are the examples of what I've tried so far.

//Gives me a download prompt.
return File(document.Data, document.ContentType, document.Name);

//Opens if it is a known extension type, downloads otherwise (download has bogus name and missing extension)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);

//Gives me a download prompt (lose the ability to open by default if known type)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name};

Any suggestions?


Source: (StackOverflow)

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I have following section defined on my _Layout.cshtml

@RenderSection("Scripts", false)

I can easily use it from a view as follows :

@section Scripts { 
    @*Stuff comes here*@
}

What I am struggling is how to get some content injected inside this section from a partial view.

Let's assume following is my view page :

@section Scripts { 

    <script>
        //code comes here
    </script>
}

<div>
    poo bar poo
</div>

<div>
  @Html.Partial("_myPartial")
</div>

I need to inject some content inside Scripts section from _myPartial partial view.

do you have any idea how?


Source: (StackOverflow)

How to set value of input text using jQuery

I have an input text which is this:

<div class="editor-label">
    @Html.LabelFor(model => model.EmployeeId, "Employee Number")
</div>

<div class="editor-field textBoxEmployeeNumber">
    @Html.EditorFor(model => model.EmployeeId) 
    @Html.ValidationMessageFor(model => model.EmployeeId)
</div>

I want to set the value of this input text using jquery so i did this:

<script type="text/javascript" language="javascript">
    $(function() {
        $('.textBoxEmployeeNumber').val("fgg");
    });
</script> 

however, it is not working... what is the error in my syntax?


Source: (StackOverflow)

ViewBag, ViewData and TempData

Could any body explain, when to use

  1. TempData
  2. ViewBag
  3. ViewData

I have a requirement, where I need to set a value in a controller one, that controller will redirect to Controller Two and Controller Two will render the View.

I have tried to use ViewBag, the value gets lost by the time I reach Controller Two.

Can I know when to use and advantages or disadvantages?

Thanks


Source: (StackOverflow)