How to specify different Layouts in the ASP.NET MVC 3 razor ViewStart file? Wednesday, Dec 7 2011 

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?

Solution:

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

@{     Layout = "~/Views/Shared/_PublicLayout.cshtml"; } 

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{     Layout = "~/Views/Shared/_StaffLayout.cshtml"; } 

You could also specify which layout should be used when returning a view inside a controller action but that’s per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel); 

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.

Dynamically add button, textbox, input, radio elements in html form using JavaScript. Friday, Nov 4 2011 

Adding Elements like textbox, button, radio button etc in a html form using JavaScript is very simple. JavaScript’s document object has a method called createElement() which can be used to create html elements dynamically.

We had used this function in our tutorial: Dynamic combobox-listbox-drop-down using javascript to add dynamic options to a combo box-listbox. Let us use this function to create textboxes, radio buttons, buttons etc dynamically and add them in our page.

Following is the source code of our example.

 

<HTML>

<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add(type) {
    //Create an input type dynamically.
    var element = document.createElement("input");
    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);
    var foo = document.getElementById("fooBar");
    //Append the element in page (in span).
    foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<SELECT name="element">
    <OPTION value="button">Button</OPTION>
    <OPTION value="text">Textbox</OPTION>
    <OPTION value="radio">Radio</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar">&nbsp;</span>
</FORM>
</BODY>
</HTML>

Append text in TextArea at cursor location using Javascript Monday, Sep 19 2011 

I have a TextArea, textBox and a button. TextArea has some text e.g This is a cat.

Now my requirement is If someone set cursor position in TextArea and enter text in textbox and click on button the text should be append in cursor position instead of last. e.g.

TextArea: This is a cat.

Cursor position: after “a” Entered Text in TextBox: black

Output: This is a black cat.

 

function insertTextAtCursor(el, text) {
var val = el.value, endIndex, range;
if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
endIndex = el.selectionEnd;
el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
el.focus();
range = document.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}

 

That's it.

 

Scaffolding – ASP.NET, NuGet, Entity Framework Code First and More Tuesday, Sep 6 2011 

Watch video by Steve here:

http://channel9.msdn.com/Events/MIX/MIX11/FRM13/player?w=960&h=544

How to enumerate FormCollection in ASP.NET MVC? Wednesday, Aug 31 2011 

Here are 5 ways to do it specifically with a FormCollection object.

public ActionResult SomeActionMethod(FormCollection formCollection)
{
  foreach (var key in formCollection.AllKeys)
  {
    var value = formCollection[key];
  }

  foreach (var key in formCollection.Keys)
  {
    var value = formCollection[key.ToString()];
  }

  // Using the ValueProvider
  var valueProvider = formCollection.ToValueProvider();
  foreach (var key in valueProvider.Keys)
  {
    var value = valueProvider[key];
  }


foreach(var key in Request.Form.AllKeys)
{
   var value = Request.Form[key];
}
foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
{
    string htmlControlName = kvp.Key;
    string htmlControlValue = kvp.Value.AttemptedValue;
}
}







C# Razor Syntax Quick Reference Tuesday, Aug 30 2011 

I gave a presentation to another team at Microsoft yesterday on ASP.NET MVC and the Razor view engine and someone asked if there was a reference for the Razor syntax.

It turns out, there is a pretty good guide about Razor available, but it’s focused on covering the basics of web programming using Razor and inline pages and not just the Razor syntax.

So I thought it might be handy to write up a a really concise quick reference about the Razor syntax.

Syntax/Sample Razor Web Forms Equivalent (or remarks)
Code Block
@{ 
  int x = 123; 
  string y = "because.";
}
<%
  int x = 123; 
  string y = "because."; 
%>
Expression (Html Encoded)
<span>@model.Message</span>
<span><%: model.Message %></span>
Expression (Unencoded)
<span>
@Html.Raw(model.Message)
</span>
<span><%= model.Message %></span>
Combining Text and markup
@foreach(var item in items) {
  <span>@item.Prop</span> 
}
<% foreach(var item in items) { %>
  <span><%: item.Prop %></span>
<% } %>
Mixing code and Plain text
@if (foo) {
  <text>Plain Text</text> 
}
<% if (foo) { %> 
  Plain Text 
<% } %>
Mixing code and plain text (alternate)
@if (foo) {
  @:Plain Text is @bar
}
Same as above
Email Addresses
Hi philha@example.com
Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Explicit Expression
<span>ISBN@(isbnNumber)</span>
In this case, we need to be explicit about the expression by using parentheses.
Escaping the @ sign
<span>In Razor, you use the 
@@foo to display the value 
of foo</span>
@@ renders a single @ in the response.
Server side Comment
@*
This is a server side 
multiline comment 
*@
<%--
This is a server side 
multiline comment
--%>
Calling generic method
@(MyClass.MyMethod<AType>())
Use parentheses to be explicit about what the expression is.
Creating a Razor Delegate
@{
  Func<dynamic, object> b = 
   @<strong>@item</strong>;
}
@b("Bold this")
Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details.
Mixing expressions and text
Hello @title. @name.
Hello <%: title %>. <%: name %>.

Notice in the last example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s trying to call a method or property of the expression.

Let me know if there are other examples you think should be placed in this guide. I hope you find this helpful.

 

 

Reflection in .Net with a C# example Monday, Jul 18 2011 

Reflection is the ability of the .NET framework to gather information (metadata) about assemblies, modules and types at runtime. It allows you also to dynamically create instances of types, invoke methods and access fields, properties and attributes.

Reflection is an important capability of the .NET framework and enables you to get information about objects at runtime. In this article, we will iterate through all properties for a class named Person using reflection.

using System;
using System.Reflection;

class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Age = 27;
person.Name = “Fernando Vezzali”;

Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(“{0} = {1}”, property.Name, property.GetValue(person, null));
}

Console.Read();
}
}

The Person class extends System.Object and does not implement any interface. It is a simple class used to store information about a person:

class Person
{
private int age;
private string name;

public int Age
{
get { return age; }
set { age = value; }
}

public string Name
{
get { return name; }
set { name = value; }
}
}

 

Common SELECT Statements (SQL Server) Monday, Jul 18 2011 

Followings are some examples of using SELECT statement. My table name tblTest. Followings are columns. (TestID, TestName, TestDate, TestCity )

1) Select * from tblTest (Returns all columns/Rows)

2) Select * from tblTest Where TestID=2 (Returns the row/s which TestID has value 2)

3) Select * from tblTest where TestID Between 10 and 20 (Return all rows between 10 and 20, this result includes 10 and 20)

4) Select * from tblTest Where TestCity in (‘New York’,’Washington’,’California’) (Returns all rows which city is NewYork, Washington, california)

5) Select * from tblTest Where TestName Like ‘A%’ (Return all rows where the name starts letter A)

6) Select * from tblTest Where TestName Like ‘%A’ (Return all rows where the name ends letter A)

7) Select * from tblTest Where TestName Like ‘[ABC]%’ (Return all rows of name start with A / B / C)

8) Select * from tblTest Where TestName Like ‘[^ABC]%’ (Return all rows of name not start with A and B and C)

9) Select (TestName+space(1)+TestCity) as Address from tblTest (Returns single column address, name and city added together with a space)

10) Select * from tblTest Where TestName IS NULL (Return all rows which TestNane has null values)

11) Select * from tblTest Where TestName IS NOT NULL (Return all rows which TestNane has not null values)

12) Select * from tblTest Order By TestID Desc (Sort the result set descending order, Asc or not using any sort Ascending order)

13) Select ‘Visual Studio’ as IDE, ‘2010’ as Version (Creating memory resident result set with two columns[IDE and Version])

14) Select Distinct TestID from tblTest (Returns unique rows based on TestID)

15) Select Top 10 * from tblTest  (Return 10 customers randomly)

16) Select getdate() (Shows the current date)

17) Select db_name() (shows the database name which you are working on)

18) Select @@Servername (Shows name of the server)

19) Select serverproperty (‘Edition’) (You can pass following ServerName, Edition, EngineEdition, ProductLevel to get current information about the server)

20) Select user_name() (Get current user)

21)  Select *  into #test from tblTest  (Create temporary table #test and insert all records from tblTest)

22)  Select Max(TestID) from tblTest (Returns Maximum TestID from tblTest)

23)  Select * from tblTest Compute Max(TestID) (Returns two result sets – getting all rows and maximum value of TestID)

24) Select FirstName, LastName,  Salary, DOB,

Case Gender
When ‘M’ Then ‘Male’
When ‘F’ Then ‘Female’
End
From Employees

(This Change Gender fields as if M then prints Male and if F then prints Female)  

SQL SERVER – Delete Duplicate Records – Rows Wednesday, Jun 15 2011 

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

To download new features in ASP.Net 4.0 click here. Wednesday, Jun 15 2011 

 

To download new features in ASP.Net 4.0 click here.

Next Page »

Follow

Get every new post delivered to your Inbox.