Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 42 - Opening a page in new browser window in mvc application

Suggested Videos 
Part 39 - ListBox in mvc
Part 40 - Using displayname, displayformat, & scaffoldcolumn attributes
Part 41 - Using datatype and displaycolumn attributes

In this video, we will discuss opening URL's in a new window. Along the way, we also discuss using UIHint attribute. Please watch Part 41, before proceeding. We will be using the same example that we started in Part 40 of this video series.

Changes to Employee.cs class file in Models folder
public partial class Employee

public class EmployeeMetaData
    public string PersonalWebSite { get; set; }

Details action method in HomeController
public ActionResult Details(int id)
    SampleDBContext db = new SampleDBContext();
    Employee employee = db.Employees.Single(x => x.Id == id);
    return View(employee);

Code in Details.cshtml view
@model MVCDemo.Models.Employee

    ViewBag.Title = "Details";


At this point, buid the application and navigate to localhost/MVCDemo/Home/Details/1. When you click on the personal website link, the target page will open in the same window.

If you want the page to open in a new window,
1. Right click on "Views" folder, and add "Shared" folder. 
2. Right click on "Shared" folder, and add "DisplayTemplates" folder. 
3. Right click on DisplayTemplates folder, and add a view. Set "Url" as the name and use Razor view engine.
4. Copy and paste the following code in Url.cshtml view
<a href="@ViewData.Model" target="_blank">@ViewData.Model</a>

That's it. Build the application and click on the link. Notice that, the page, now opens in a new window. The downside of this approach is that, from now on all the links, will open in a new window. To overcome this, follow these steps.
1. Rename Url.cshtml to OpenInNewWindow.cshtml
2. Decorate "PersonalWebSite" property in EmployeeMetaData class with UIHint attribute and specify the name of the template to use. In our case, the name of the template is "OpenInNewWindow".
public class EmployeeMetaData
    public string PersonalWebSite { get; set; }

So, UIHint attribute is used to specify the name of the template to use to display the data field.

1 comment:

  1. Thats it for today.Thank you for listening. Have a great day....

    I am having a great day after going through this tutorials


If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.