Infolink

 

Search This Blog

Showing posts with label mvc. Show all posts
Showing posts with label mvc. Show all posts

Nov 28, 2012

How to create a simple model in ASP.NET MVC and display the same?(PART-4)

Step1:- Create a simple class file

The first step is to create a simple customer model which is nothing but a class with 3 properties code, name and amount. Create a simple ASP.NET MVC project, right click on the model folder and click on add new item as shown in the below figure.


Nov 18, 2012

MVC Tutorial (PART-1)

The Model

Models are the main component of your app, which is usually; what is stored and retrieve from the database, in our app, it will the tweet info and text.

The View

Views are the date in formatted form, delivered to the user. Here it will be the HTML pages.

The Controller

Controllers are the components that respond to all user requests, decide the appropriate response; which might be render a view, redirect to other URI or many other things.

Pros and Cons
 
Pros

It has many pros, but these are the most remarkable:
  • Full control over the HTML, CSS, and JavaScript code, helping you to write clean, standards-compliant markup
  • It's Extensible which means that you can use a default component, or reconfigure it, or even use another component
  • HTTP friendly, it gives you total control over the requests passing between browser and server
  • Testability of MVC makes it simple to unit test the logic that is specific to a page, by testing controller methods
Cons 

It does not really have many cons compared to its pros:
  • The lake of drag and drop component in WebForms, despite that JQuery and other JavaScipt library overcome this problem
  • It's not as easy as WebForms, you should understand the role of each component individually and all of them together.

Nov 7, 2012

DockPanel in Silverlight

If you have used docking Windows in previous versions of .NET, the DockPanel is used to provide that functionality in WPF and Silverlight. The DockPanel is not a part of Silverlight 2. It is a part of Silverlight Toolkit but I am sure it will be a part of the next version of Silverlight.

The DockPanel control is a layout control that acts as a container for child controls. The DockPanel allows child controls to dock in left, right, top, or bottom sides of the panel.

Oct 21, 2012

How to Detect Errors of Our ASP.NET MVC Views on Compile Time

I have simple ASP.NET MVC 4 internet application which we get out of the box (Things that I will show can be applied with ASP.NET MVC 3 as well). Then I will put a bug inside the index view of my home controller :

@{
    var poo = "bar"
    }

<h3>We suggest the following:</h3>
As you can see it is not a valid code. So it should fail on both compile time and runtime, right? Let’s build the project first :

Error1

When to use ViewModel in mvc3

In asp.net mvc, a controller can pass single object to the corresponding view. This object may be a simple object or a complex object. ViewModel is a complex object that may contain multiple entities or objects from different data models or data source. Basically ViewModel is a class that specify data model used in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Designing the model

public class UserLoginModel
{
[Required(ErrorMessage = "Please enter your username")]
[Display(Name = "User Name")]
[MaxLength(50)]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter your password")]
[Display(Name = "Password")]
[MaxLength(50)]
public string Password { get; set; }
}


Working with Enums and Templates In ASP.NET MVC

Imagine you have the following types defined.

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public MovieGenre Genre { get; set; }
}

public enum MovieGenre
{
    Action,
    Drama,
    Adventure,
    Fantasy,
    Boring
}

If you want to display MovieGenre, the DisplayFor helpers generally give you what you expect (i.e. @Html.DisplayFor(m=> m.Genre) displays "Adventure"), but EditorFor will only give you a text input because the framework treats an enum the same as a string.

Oct 20, 2012

Configuring Multiple End points for WCF Service

Sample Service with multiple End Points

Step 1

Create a WCF Service Application. Open Visual studio and create new project selecting WCF Service Application project template. In VS2008, you will get WCF Service Application project template inside WEB tab whereas in VS2010, you will get WCF Service Application project template inside WCF tab.

Step 2

Delete the default code getting created for you by WCF. Delete all the code from IService1 and Service1. If you are using VS2008, comment out whole System.ServiceModel from Web.Config file. And if you are using VS2010 then comment out Multiple Host Binding.

Step 3

Oct 19, 2012

ASP.NET Trace

Trace.Write helps diagnose problems in ASP.NET. It determines what is actually running in an ASP.NET application. We review the basics of tracing in ASP.NET. We use the C# language to easily benchmark sites.

First we must add the trace markup to our Web.config file. The sample values in the markup I show can and should be changed by you. I encourage you to flip the attribute values and see what they do as much as possible. Here's how to add the markup.

Open Web.config file. Your ASP.NET project should have a Web.config file. If it doesn't, add one through the Website > Add New Item.... menu. This is an XML file used by ASP.NET to store website configuration settings.

Oct 18, 2012

Generics classes Overview in C#.Net

Generics main benefit is eliminating boxing and unboxing that is true, there are also other benefits like type safety, by using generics you eliminate type ambiguitiy.

  1. Generics provide type safety without the overhead of multiple implementations. Ex. We can create a linked list of string. LinkedListlinkList=new LinkedList(); There is no need to inherit from a base type and override members.The linked list is ready for immediate use.
  2. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
  3. Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types
  4. Generic delegates enable type-safe callbacks without the need to create multiple delegate classes.  

Oct 17, 2012

C# KeyNotFoundException

A KeyNotFoundException was thrown. This is likely caused by an invalid usage of the Dictionary collection. As always we want a quick way to fix the problem.

Example

First, here we see some code that looks correct, but actually has a severe flaw. The problem is that you cannot look up a key that doesn't exist in the Dictionary and try to assign your variable to its value.

The KeyNotFoundException here is thrown on the final line of try-block. The string "test" doesn't exist in the collection.

Program that throws KeyNotFoundException [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    try
    {
        //
        // Create new Dictionary with string key of "one"
        //
        Dictionary<string, string> test = new Dictionary<string, string>();
        test.Add("one", "value");

        //
        // Try to access key of "two"
        //
        string value = test["two"];
    }
    catch (Exception ex)
    {
        //
        // An exception will be thrown.
        //
        Console.WriteLine(ex);
    }
    }
}

Output

System.Collections.Generic.KeyNotFoundException:
    The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()

Fix

Here we look at how you can fix this exception by using the TryGetValue method on the Dictionary constructed type. Note that could use ContainsKey instead of TryGetValue, but the below code preserves the intention of the previous code.

Program that does not throw [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    Dictionary<string, string> test = new Dictionary<string, string>();
    test.Add("one", "value");
    //
    // Use TryGetValue to avoid KeyNotFoundException.
    //
    string value;
    if (test.TryGetValue("two", out value))
    {
        Console.WriteLine("Found");
    }
    else
    {
        Console.WriteLine("Not found");
    }
    }
}
Output

Not found

You always have to use the if statement when testing values in the Dictionary, because there is always a possibility that the key won't exist.

We saw how to raise and catch the KeyNotFoundException during runtime. We then saw how to avoid causing the exception. We discussed alternatives, such as TryGetValue and ContainsKey, and looked at a program that does not have this problem.

Oct 14, 2012

User Control Example

In this example I show that how easily we can create User Control and then use it in asp.net. Here first I create a User Control name CalendarUserControl.ascx, then place it Default.aspx web form. Here is the source code of both files.

Aug 24, 2012

Levels Of Abstraction In An MVC View

Working on a dashboard I came across a view arranged like the following diagram:




The scenario is simplified because there is more to do inside of one block than just @SomeOutput, but focus on the structure of the view. I needed to add some more behaviors to the dashboard using CSS and script code, but it only took a few minutes to achieve frustration. Sometimes the view would delegate to a partial view for a specific section of the dashboard, and sometimes the view would inline all the markup and code for a section. Then there was also the odd case of having one partial view responsible for two entire sections of the dashboard, which threw me off entirely. Being new to the code it took some time to figure out how the pieces worked together to produce the page.

Before I started making my own changes, I did a little refactoring to structure the view like so ...



... and then development life was easier. The mental model of how to map from implementation to output was simplified, and I instantly knew where to go to make different changes.

There are a number of ways you could spin this story. You could argue how the original view violated the single responsibility principle since it was taking responsibility for providing the structure of the dashboard and rendering some of the details. I'd agree with this argument. You could also argue the original view violated the single level of abstraction principle, and I'd agree with that argument, too.

In the end I simply liked the solution better because it seemed simple and symmetrical. Not many people talk about the aesthetic qualities of balance and symmetry in code, but I think it is a sign of craftsmanship that can benefit software by making code easier to understand and maintain. I bet the dashboard changes again in 3 months, and hopefully the next person has an easier time making those changes.

 
Related Posts Plugin for WordPress, Blogger...