Multiple Models in a View in ASP.NET MVC4/MVC5

As a beginner in ASP.NET MVC, the most common question is how to pass multiple models in a view. There are two common ways to achieve the same output. However, there are a lot of ways of using multiple models in a view, these are:

  • ViewData
  • ViewBag
  • PartialView
  • TempData
  • ViewModel
  • Tuple

 

All the above  ways of using multiple models in view have their own place. However, we need to think which of these is right for our requirements. All these techniques have their own advantages and disadvantages.

To understand it better, download the attached code in the blog.

Read the rest of the post here: http://www.codeproject.com/Articles/687061/Using-Multiple-Models-in-a-View-in-ASP-NET-MVC-4-M

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

How to Prevent SQL Injection Attacks in ADO.NET

The following lines of code are causing a SQL Injection Attack:

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string Command=“Select * from tblProductInventory where ProductName like ‘”+TextBox1.Text     + “%’”;
    SqlCommand cmd = new SqlCommand(Command, con);
    con.Open();
    GridView1.DataSource = cmd.ExecuteReader();
    GridView1.DataBind();
}

We can avoid SQL injection attacks in two ways:

  1. Using parameterized queries
  2. Using stored procedures

Through parameterized queries, the code above can be written in this format to prevent SQL injection attack:

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
// Parameterized query. @ProductName is the parameter
  string Command = “Select * from tblProductInventory _<br />  where ProductName like @ProductName”;SqlCommand cmd = new SqlCommand(Command, con);
// Provide the value for the parameter
    cmd.Parameters.AddWithValue(“@ProductName”, TextBox1.Text + “%”);
    con.Open();
    GridView1.DataSource = cmd.ExecuteReader();
    GridView1.DataBind();
}

SQL injection can also be prevented using stored procedures like so:

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
// The command that we want to execute is a stored procedure,
// so specify the name of the procedure as cmdText
    SqlCommand cmd = new SqlCommand(“spGetProductsByName”, con);
// Specify that the T-SQL command is a stored procedure
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
// Associate the parameter and it’s value with the command object
    cmd.Parameters.AddWithValue(“@ProductName”, TextBox1.Text + “%”);
    con.Open();
    GridView1.DataSource = cmd.ExecuteReader();
    GridView1.DataBind();
}

Read the rest of the explanation in this blog post: http://www.codeproject.com/Articles/732429/ADO-NET-How-to-Prevent-SQL-Injection-Attack-2

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

MVC and Asynchronous Calls

When we want to issue requests to controller actions from a view, some sections without having to load the whole page and at the same time experience page flickering. The solution to this problem is to make asynchronous request. You can do this with MVC Ajax Helper and JQuery.

First, you have to make sure that MVC project has a bundle script for your JQuery version. You should have a code similar to this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

Then in the _Layout view under the shared folder should have a code like this:

 @Scripts.Render("~/bundles/jquery")

These are a part of the bundling and minification of ASP.NET MVC.

To learn more about this tutorial, read this blog: http://www.codeproject.com/Tips/732183/MVC-and-Asynchronous-Calls

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

[ASP.NET MVC] Model Binding to List Of Objects

Showing a single record for editing is common and the default model binding of ASP.NET MVC takes care of mapping the form to the model properties. But, there are times where you need to edit multiple records, like when you want to display an editable grid to the end user filled with existing data. The user can edit values from multiple rows then hit save to attempt to save the data. In this case, multiple objects are submitted and is no longer valid. By tweaking form field names, you can get this to work as expected.

First, create an new ASP.NET MVC application then follow this guide: http://www.dotnetbips.com/articles/b1e0b153-47f4-4b29-8583-958aa22d9284.aspx

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

How to Interleave 2 HTML Files into One .DOCX File

The killer question is: Why combine two files into one?

In case you want to compare two HTML documents into one. Say for example you want to learn a new language. The easiest method to do that is to have one language in one hand, and the other language to the other. There are also other useful ways you can take advantage of this.

In this tip, you will need to NuGet the HTMLAgilityPack and the DOCX library.

What you will end up is not exactly as beautiful as you expect it to be but it does the work well.

Read the rest of the tutorial here: http://www.codeproject.com/Tips/729218/How-to-interleave-two-HTML-files-into-one-DOCX-fil

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Mastering .NET Math with ILNumerics

ILNumerics is a high performance math library made for programmers and scientist. It extend the .NET framework with tools required for scientific computing. It also simplifies the implementation of all kinds of algorithms in a convenient, familiar C# syntax that is optimized for the speed of C and FORTRAN.

This guide will help you get started with ILNumerics. This assumes that you already have ILNumerics installed in your project using NuGet.

If not, ILNumerics is available in two editions: Professional and Community Edition. The Community Edition is a free and open source mostly used for academic purposes. The professional edition, is a closed source license that has prebuilt binaries under a proprietary close license.

Read the rest of the post here: http://channel9.msdn.com/coding4fun/blog/Mastering-your-Net-Math-needs-with-ILNumerics

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Custom HTML Helper for MVC Application

How many times you wonder on how to avoid writing the same HTML/JavaScript code many times in an MVC Razor view? What if this repetitive task can be as simple as building a custom HTML helper to encapsulate everything and make repetitive task less arduous.

So, let’s say we want to avoid doing this code many times in your views:

<img src="@myModel.MyObject.ImageSource", alt ="@myModel.MyObject.Imagename",
title ="@myModel.MyObject.ImageDescription" />

So you want something Razor like that may take care of some logic or validation error in the previous snippet.

@Html.Image(@myModel.MyObject.ImageSource, 
@myModel.MyObject.Imagename, @myModel.MyObject.ImageDescription)
namespace MyNamespace 
 {  
    public static class MyHeleprs
    { 
        public static MvcHtmlString Image(this HtmlHelper htmlHelper, 
        	string source, string alternativeText)
        {
            //declare the html helper 
            var builder = new TagBuilder("image"); 
            //hook the properties and add any required logic
            builder.MergeAttribute("src", source);
            builder.MergeAttribute("alt", alternativeText);
            //create the helper with a self closing capability
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        } 
    } 
}

Read the rest of the code here: http://www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

How to Create a Web Service in ASP.NET

A web service is a web application that is available on the internet. It uses XML format for all the communication with other applications on the internet. A web application uses XML and JSON data formats and HTTP protocol to communicate with other applications on the internet.

So let’s say you have created an application that can convert string into uppercase. If you want it to be used by other applications on the internet, it has to be converted to a web service and should be deployed on the net.

In this article, you will learn about web  service in ASP.NET and how it communicates with other web applications.

Read the rest of the post here: http://www.codeproject.com/Tips/719710/You-can-do-it-How-to-Create-a-Web-service-in-ASP-N

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Implementing 5 Principles of REST using WCF Services

REST is just using the current feature of the ‘Web’ in a simple, yet effective manner. Some amazing features of the Web are:

  1. Standard and unified methods like POST,GET,PUT and DELETE
  2. Matured and widely accepted HTTP protocol.
  3. Stateless nature of the HTTP protocol.
  4. Easy to use URL format to locate any web resource.

There are 5 basic fundamentals of the web in which REST are leveraged:

Principle 1: Everything is a Resource.

Principle 2: Every resource is identified by a unique identifier.

Principle 3: Use simple and uniform interfaces.

Principle 4: Communication is done by representation.

Principle 5: Be stateless

 

Read the complete explanation in this post: http://www.codeproject.com/Articles/283550/Implementing-5-important-principles-of-REST-using

 

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

Dependency Injection for Beginners

Dependency Injection is a software development pattern to resolve the following problems. Below is a code that will better explain this:

Public class client
{
     Public static void main()
     {
        NeedDependencyClass a = new NeedDependencyClass();
     }
}

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass ()
  {
     _b = new DependencyClass();
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}

The problem with this code is that:

1. Class NeedDependencyClass is responsible for creating its own dependency.

2. Code violates the “Open Closed” rule of SOLID principal that says “software entities should be open for extension but closed for modification.

3. Code is tightly coupled because the dependency cannot be replaced.

4. Testing NeedDependencyClass becomes difficult because it cannot replace dependency class DependencyClass with other dependencies.

Read the solution in this blog: http://www.codeproject.com/Articles/719563/Dependency-Injection-For-Beginner-1

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS