Friday, December 12, 2014

Upload Files to Local Folder in MVC

 public ActionResult LoadData(HttpPostedFileBase importfile)
        {
            var fileName = importfile.FileName;
       
           string    filePath = "~/Uploaded_Files/";

           var path = Server.MapPath("~/Uploaded_Files/") + fileName;

           importfile.SaveAs(path);
}

Monday, December 8, 2014

The underlying provider failed on Open in Dotnet

Solution:

Please Check the Web.config and App.config connection strings.

How to Upload Images in MVC

View:
-------

UpImage1.cshtml:

@{
    ViewBag.Title = "UpImage1";
}

<h2>UpImage1</h2>
@using (Html.BeginForm("UpImage1", "Home", FormMethod.Post,
                            new { enctype = "multipart/form-data" }))
{
    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" style="width: 100%;" />
    <input type="submit" value="Upload" class="submit" />
}

Action:
--------


        public ActionResult UpImage1()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UpImage1(HttpPostedFileBase file)
        {
            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                string path = System.IO.Path.Combine(
                                       Server.MapPath("~/images/"), pic);
                // file is uploaded
                file.SaveAs(path);

                // save the image path path to the database or you can send image
                // directly to database
                // in-case if you want to store byte[] ie. for DB
                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    byte[] array = ms.GetBuffer();
                }

            }
            // after successfully uploading redirect the user
            return RedirectToAction("Index", "Home");
        }

Monday, December 1, 2014

Advantages and Disadvantages of Entity Framework in .NET

The EF is essentially an O/R mapping tool. It takes care of object persistence for you. In other words, it acts as your data layer. writing applications using entity framework saves lot of development time and its good..if we are developing enterprise applications, we need to think about performance..all in all its good for small applications..

  1. Advantages : One common syntax ( LINQ / Yoda ) for all object queries whether it is database or not , Pretty fast if used as intended , easy to implement SoC , less coding required to accomplish complex tasks
    Disadvantages : you have to think in a non traditional way of handling data , not available for every database
  2. Disadvantage: If there is any schema change in database FE won’t work!!! You have to update the schema in solution as well!!!
    Advantage: Its fast and straight forward using LINQ/FE objects For Add/Modify/Delete/Update.
  3. Advantages:-Easy to map business objects (with drag & drop tables on environment).
    -It keeps a good performance when you work with a small / middle domain model.
    Disadvantages:-It's limited when you work with a huge domain model.
    -Scalability.
After getting dig into this topic, One question comes in our mind that is “Entity Framework vs. LINQ to SQL”
  • LINQ to SQL is the quick-and-easy way to do it. This means you will get going quicker, and deliver quicker if you are working on something smaller.
  • Entity Framework is the all-out, no-holds-barred way to do it. This means you will take more time up-front, develop slower, and have more flexibility if you are working on something larger.
  • LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.
  • LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.
  • Linq-To-Sql - use this framework if you plan on editing a one-to-one relationship of your data in your presentation layer. Meaning you don't plan on combining data from more than one table in any one view or page.
  • Entity Framework - use this framework if you plan on combining data from more than one table in your view or page. To make this clearer, the above terms are specific to data that will be manipulated in your view or page, not just displayed. This is important to understand.

How to Get Count of Repeated Values From a Table In SQL SERVER

Solution:

SELECT CityName, COUNT(*) CityName
FROM Cities
GROUP BY CityName
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

Wednesday, November 19, 2014

SQL Server:Inner Join using 'Where' 'Is Not Null' and sorting conditions




SELECT Table1.weborder, Table2.weborder,Table2.web_promocode,Table2.web_cost,Table2.web_price,Table2.web_quantity,Table1.web_ordertime,Table2.web_unitcost
FROM Table1
INNER JOIN web_details
ON Table1.weborder=Table2.weborder where Table2.web_promocode is not null and Table2.web_ordertime>'11/01/2014' and Table2.web_unitcost>0
ORDER BY Table1.web_ordertime desc;

Not Equal to Null or Is Not Null Condition in SQL Server

Query:

select * from Employeetable where emp_date is not null

Thursday, November 13, 2014

Application Object Tree in AX

The Application Object Tree (AOT) is the development menu in Axapta. All objects used in the application are stored in the AOT and presented to the developer in a tree organized by object type. Axapta uses a layer technology to store objects. This layers help differentiate the objects in Axapta as a typical Axapta installation is built up using not just the standard objects from Microsoft, but also objects provided by Solution Providers, partners and as those developed by customers themselves.  
When expanding a node in the AOT, the sub nodes at the next level will be cached. This may take a few seconds the first time a node is expanded. You only cache the nodes used. When a cached node is later expanded you will find that it responds far more quickly.  
The AOT is accessed by pressing ctrl+d or clicking the icon  in the top menu. Notice that if you are running a demo installation of Axapta, you will not have access to the AOT. You must have the license codes  and X++ installed.
To create a new object, right-click a node in the AOT and choose new. A red vertical bar next to the object node indicates that the node has not been saved. The red mark is also set when a node is modified. All nodes modified or recently created can be saved by clicking the save all icon  in top of the AOT window.
Objects, fields and methods may be duplicated within the AOT. Methods and fields may also be copied. The copy and duplicate functions are accessed by right-clicking on the node and selecting the desired function. When you duplicate a node, the system will create a copy of the selected node in the AOT prefixed with copyOf. This is especially useful when you want to test a possible modification and would like to preserve the prior state of the object as a fallback should the change not function as desired.  
The AOT also supports drag and drop. When adding controls to forms and reports, it is often much faster to drag the fields used for the controls to the form or the report directly from a data source, rather than create them from scratch.
Regardless of which node you select in the AOT, you will always have access to a context menu by right-clicking the current node. The menu is named SysContextMenu in the AOT and can be found under the Menu node. When browsing the menu from the AOT all menu items available in the Context menu will be listed. Depending on the selected node in the AOT you will have additional menu items available to perform context specific activities, like creating a new object, opening a new window or accessing the tools sub menu Add-Ins. Opening a new window provides a root node based on the current selected node in the AOT. You can open as many windows as needed. This feature can be used while dragging new objects to a form or a report, or simply to have cursors positioned in different places in the AOT.   

Thursday, November 6, 2014

How to create Item or Product and Product master in Dynamics AX 2012

Here we are going to discuss how to create a product and Product master(Items).
In 2012, ‘Item’ is replaced with ‘Product’. One cannot find an item master in Inventory Management Module, there is a separate module for item/product creation. The Name of that module is ‘Product Information Management’.
There are two types of Products in 2012. They are
1. Product
2. Product Master
1. Product:
These are clearly identifiable products that do not have variations associated with them. You can think of them as standard or base products. Use the Products list page in the Product information management module to view and manage products.
2. Product Master:
These serve as templates or models for variants. The variants of a product master can be either predefined or created in sales scenarios by using a product configurator. A product master is associated with one or more product dimensions, or for some configurators, product attributes. Use the Product master’s list page in the Product information management module to view and manage product masters
To access Product and Product Masters go to Product Information Management à Common Forms à Products à Products /Products Masters.
 
Product Creation Process:
  • To create product go to Product Information Management à Common Forms à Products à Products.
  • Click on New Button, a new product form is opened. In that form select the product type as Item/Service.
    • Item- A Tangible item which has inventory transactions and On-hand inventory.
    • Service- an Intangible item which has no On-hand inventory.
    • Now select Product sub-type, (note- if you open new product form from ‘all products and product master’ then you will be displayed with two option product/product masters in this drop down menu)
    • Enter Product Number.
    • Press ok and the current form closes and a new line is created in the products list page.

Product/Product Master Creation Process:
  • To create product go to Product Information Management à Common Forms à Products à Products.
  • Click on New Button, a new product form is opened. In that form select the product type as Item/Service.
    • Item- A Tangible item which has inventory transactions and On-hand inventory.
    • Service- an Intangible item which has no On-hand inventory.
    • Now select Product sub-type, (note- if you open new product form from all products and product master  then you will be displayed with two option product/product masters in this drop down menu)
    • Enter Product Number and all the related fields.
    • In the product variants section, select product dimensions group and configuration technology.
    • Press ok and the current form closes and a new line is created in the products list page.


Assigning Dimensions Groups to a Product Master:
  • In the product list page, double click on the product.
  • In the product details form opened, on the top of the form you will find Dimension Group Button.
  • Click on Dimensions group Button will open a drop down menu.
  • In the drop down menu you find three fields
    • Product Dimension group
    • Storage Dimension group
    • Tracking Dimension group
    • Select the appropriate groups from these menus.
 
Note:
Please don’t get confused between a ‘Product’ and ‘Product Master’; they are two different product types in AX 2012.
We can assign Product ‘Dimension Group’ to ‘Product Master’ but we can’t assign ‘Dimension Group’ to ‘Product’. ‘Product’ is a unique item which doesn’t have any variants.
Creating Product Dimensions and creating dimension combinations:
  • In the product details form, in the product master field press product dimensions button.
  • In the Product dimensions form in the left pane, all the dimensions related to that product will be displayed.
  • Click on one dimension, the right pane will display the dimension already entered if any.
  • If you are entering dimensions for the first time, the right pane will be empty.
  • Now press new button, a new blank line is created. Enter the dimensions.
  • For example, if you select configuration in the left pane then enter the configuration dimension of the product in the right pane.
  • Similarly repeat the steps for all the product dimensions.
 
Product dimension combinations (Product Variants):
  • Once you create all the dimensions for a product, in ax 2009 we need to create item combinations.
  • Similarly in ax2012 we use Product Variants.
  • You can find product variants button in the product master section of the product master details form.
  • Please refer to the below screenshot
  • In the product variants form, you can create product dimension combinations using two methods,
    • By directly clicking on new button and selecting appropriate configurations. (OR)
    • By clicking on ‘Variant Suggestions’ will open a new form displaying all the possible combinations. Just check the select checkbox on the combinations you want and press OK.
Release product to legal entities:
  • Once you have created the product you need to release that product for use by your companies.
  • To release a product, go to that product in the product master form and on the top of the form in Product Authorization section press on ‘Release Product for Legal Entities’ button.
  • Release Products form is opened. Please see the screenshot for your reference.
 
  • In the left hand side of the form, press ‘select products’. In the right hand side, all the products will be displayed. Further right to that, you will find all the product variants.
  • Select the required products or product variants.
  • Now Press ‘Select Companies’ from left hand side pane.  All the companies in the ax will be displayed.
  • Now select the companies in which you want to use this product and after finishing press OK.
  • Now you have Released your Product for further use.
Assigning Item Model Group & Item Groups to a Product Master:
  • In the Released products form (go to product information management module à common forms à Released Products) select your product and click on ‘Edit’ button on top left.
  • In the Released product details form, in the General Fast Tab , you will find ‘Item Model Group’ Field
  • From the drop down menu, select an item model group.
  • In the same form , in ‘Manage costs’ tab posting, field you will find ‘Item Groups’ Field.
  • From the drop down menu select an Item Group.
  • Now the item or Product or Product master is ready for further transactions.

Wednesday, November 5, 2014

C#: Convert Excel File to Unreadable format or .err file

   public string Excelfilepath = string.Empty;          
Excelfilepath = @"C:\Users\abc\Desktop\xyz\pqr.xls";
FileInfo f = new FileInfo(Excelfilepath);
                string filefullname = f.Name;
                string fileextension = f.Extension;
                string filename = string.Empty;
                filename = filefullname.Substring(0, filefullname.Length - fileextension.Length);
                if (File.Exists(f.DirectoryName + "\\" + filename + ".err"))
                {
                    File.Delete(f.DirectoryName + "\\" + filename + ".err");

                }
                if (File.Exists(f.DirectoryName + "\\" + filename + ".xls"))
                {
                    f.MoveTo(Path.ChangeExtension(Excelfilepath, ".err"));
                }

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

Solution:

Application-->Properties-->Build-->Change Platform target from Any CPU to-->x86

Tuesday, October 14, 2014

How to handle Multiple Buttons in MVC using form Action


<button type="submit" id="btnSave" value="Save" formaction='/home/Method1'>Save</button>
 <button type="submit" id="btnSubmit" value="Submit" formaction='/home/Method2'>Submit</button>

How to handle Multiple Buttons in MVC

 View:
---------
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "submitForm" }))
{
@Html.TextBoxFor(m => m.Name, new { maxlength = 50 })

 <button type="submit" id="btnSave" name="command" value="Save">Save</button>
 <button type="submit" id="btnSubmit" name="command" value="Cancel"/>
}


Action:
----------
 public ActionResult Create(YourModel obj,string command)
{

//from here you can get the value of button you click
if(command="Save")
{

}
else if(command=="Cancel")
{
}
else
{
return RedirecToAction("Index");
}
return View();

}

Tuesday, October 7, 2014

MVC 5, Entity Framework 6 and Many to Many Relationship is a step by step View Model approach

Introduction

There are a lot of articles about ASP.NET MVC and Model Binder. I didn't find any real-world article about Model Binder of Many To Many relation. So I decided to write this post and share my experience on this topic. Although I will explain easily and step by step my approach, readers of this article should have as prerequisite the knowledge of basic concepts in ASP.NET MVC as Controller, View, Model, Model Binder and Scaffolding.

Background

In this post I will use ASP.NET MVC 5, Entity Framework 6.1.1 and Visual Studio 2012. To add MVC 5 support in VS2012 you have to check this link : ASP.NET and Web Tools 2013.1 for Visual Studio 2012. You can add Entity Framework 6.1.1 through NuGet. My approach should be not the best, but it works well.

Many to Many Entity Model generation

My sample comes from a real-world application, a Web Job Portal for Employers and Job Seekers. In my sample I will use Database first approach. With Entity Framework we can start our project also with First Model Approach designing the Model of our entities and after generating the database schema using Entity Framework tool. I will not add more because this is not the topic of the post. Let's carry on. We have the following database diagram
JobPost contains the job announce posted from Employer. Moreover the Employer can add to a JobPostmany JobTag. In the database those two tables are related to each other via a link or junction table, JobPost_JobTag without payload. This table just contains the foreign keys used to link the two tables together into a many-to-many relationship. We create a new ASP.NET MVC5 web project named ManyToManyMVC5
Now we have to add Entity Framework 6.1.1 from NuGet. We are ready to create a model and import these tables and relationship in onr project.
Add a new model to the project by right-clicking your Models folder and selecting Add>New>ADO.NET Entity Data Model.
  1. Specify as name for item "JobPortal"
  2. Select the option Generate from Database
  3. Use the wizard to create your database connection or connect to an existing one. Let "JobPortalEntities" as the name for the connection string of the Web.Config file ( the option on the buttom )
  4. Select the 3 tables to add to the model : Employer, JobPortal, JobTag and JobPortal_JobTag. Check the option "Pluralize or Singularize generated object names" and let other settings as default.
Now you see the Entity Diagram of the generated model
Note that we have the one-to-many relationship between Employer and JobPost, and the many-to-many relationship between JobPost and JobTag. Note that the link table JobPost_JobTag is not represented as an entity in our mode. This is because our link table it has no payload ( that is it has no scalar property ). If we had a payload, we shouldn't have the many to many relationship but we should have a fourth entity with one-to-many relationship to JobPost and one to JobTag. Let's carry on. In the Models folder we have JobPortal.edmx file, that is the phisical representation for our model. We can expand it and expand JobPortal.tt. We see that the last contains our .cs files for the entitites we generated. Take a look to JobPost.cs and JobTag.cs 

 public partial class JobPost
    {
        public JobPost()
        {
            this.JobTags = new HashSet<JobTag>();
        }
   
        public int Id { get; set; }
        public string Title { get; set; }
        public int EmployerID { get; set; }
   
        public virtual Employer Employer { get; set; }
        public virtual ICollection<JobTag> JobTags { get; set; }
    }
    public partial class JobTag
    {
        public JobTag()
        {
            this.JobPosts = new HashSet<JobPost>();
        }
   
        public int Id { get; set; }
        public string Tag { get; set; }
   
        public virtual ICollection<JobPost> JobPosts { get; set; }
    }  

Note that the two entities have a ICollection property to each other.

ASP.NET MVC5 and Many to Many relationship

Surfing internet you will find many interesting articles and posts on Model View Controller ASP.NET pattern and how it is easy to create MVC projects. But in the real-world the things are different and we have to enhance our approach.
In ASP.NET MVC we can use Scaffolding to quickly generating a basic outline of our application that we can edit and customize. So we can create automatically controllers and strong-typed view to perform basic CRUDL operations on our entities. Unfortunately ASP.NET MVC scaffolding doesn't handle many to many relationship. I think that the main reason is that there are too many kinds of many-to-many user interface creating/editing.
Another issue is concerning the automatic ASP.NET MVC Model Binding. As we know, model binding allows you to map HTTP request data with a model. Model binding makes it easy for you to work with form data because the request data (POST/GET) is automatically transferred into a data model you specify. ASP.NET MVC accomplishes this behind the scenes with the help of Default Binder. If we have a Many to Many relationship in the user interface we will have some kind of interface that allow user to perform multiple choice. So we need a complex type in our view to bind the selected items, as a Check Box Group or List, or a Multiple List Box. But let see the issues in action .
We will use Scaffolding to generate a basic controller with Entity Framework based CRUDL method and the related Views. Right click on Controlers foder and choise Add>Controller. In the Add Scaffold choise "MVC5 Controller with views, using Entity Framework". Set the next form as the below picture and click on Add
Note: If you get an error message that says "There was an error getting the type...", make sure that you built the Visual Studio project after you added the class. The scaffolding uses reflection to find the class.
MVC5 Scaffolding will generate in the Controllers folder a file JobPostController.cs and in the Views folder in the JobPost subfolder the views for the related CRUDL methods. Before run the application we have to modify the RouteConfig.cs located in App_Start setting as default controller JobPostController

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "JobPost", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Now you can run the application and browse the pages. It is amazing ...!! But .. we don't have any track about Many to Many relationship !!!

View Model Approach

To overcome these issues, my approach is based on ViewModel entity. View Model represents data you want to have displayed in your view. Easily is a class that represents data model used in a specific view. In our case our View Model contains the data of the JobPost, the data of all available JobTag and the data of the selected JobTag.
We start to modify the View Index ( it is associated to the Action index of the JobPostController ) and let it to show the list of the associated JobTag to a JobPost in a Listbox. So we add a row to the table in the index.cshtml.


// This row to the header table
 <th>
    @Html.DisplayNameFor(model => model.JobTags)
 </th>
// This row to the body table
 <td>
    @Html.ListBox("Id", new SelectList(item.JobTags,"Id","Tag"))
 </td>

Now we can run the apps ... in the index you will see a ListBox with all Tags for the post. It was easy.
Next step is to modify the edit view. When user edit a job post, we desire to show a ListBox with the list of available the job tags where the selected are the ones associated to the job post. User can change the selection or other data and submit back to the controller to persist the data,
The first problem is to pass to the view the list of all available job tags. The second problem is to mark as selected the associated ones. Now comes in the Model View !!
In your solution create a folder named ViewModel and add to it a class file "JobViewMode.cs" with the code below

public class JobPostViewModel
{
    public JobPost JobPost { get; set; }
    public IEnumerable<SelectListItem> AllJobTags { get; set; }

    private List<int> _selectedJobTags;
    public List<int> SelectedJobTags
    {
        get
        {
           if (_selectedJobTags == null)
           {
              _selectedJobTags = JobPost.JobTags.Select(m => m.Id).ToList();
           }
           return _selectedJobTags;
        }
        set { _selectedJobTags = value; }
    }
}
Our view model contains a property that store a JobPost, a property that store the JobTag associated to the stored JobPost as a List<int> of JobTag's Id, and finally a property that store all available JobTag as a IEnumerable fo SelectListItem ( to bind to a ListBox )
We modify the Action edit associated to the Get as below where we introduce the JobPostViewModel instead of JobPost

 // GET: /JobPost/Edit/5
public ActionResult Edit(int? id)
{
     if (id == null)
     {
       return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }

     var jobPostViewModel = new JobPostViewModel            {
            JobPost = _db.JobPosts.Include(i => i.JobTags).First(i => i.Id == id),
         };

     if (jobPostViewModel.JobPost == null)
        return HttpNotFound();

     var allJobTagsList = _db.JobTags.ToList();     
     jobPostViewModel.AllJobTags = allJobTagsList.Select(o => new SelectListItem
     {
                Text = o.Tag,
                Value = o.Id.ToString()
     });

     ViewBag.EmployerID =
             new SelectList(db.Employers, "Id", "FullName", jobpostViewModel.JobPost.EmployerID);
 
     return View(jobpostViewModel);
}


Note : As you modified because you have not already changed the view type model you will get an error from the retur View field. Ignore it. It will off after you will modify the related view
In the modified action method we use the JobPostView entity. We load the propertiy JobPost with the selected job post including the eager loading of JobTags entity, and the property AllJobTags with a ListIntem builded form the JobTags and return to the View the ViewModel instead of the Model. Now we can modify the View. We change the ModelBinder to ViewModelJobPost and all the property. We add the ListBox binding.
@model ManyToManyMVC5.ViewModels.JobPostViewModel
@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
   
    <div class="form-horizontal">
        <h4>JobPost</h4>
        <hr />
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.JobPost.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.JobPost.Title, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.JobPost.Title)
                @Html.ValidationMessageFor(model => model.JobPost.Title)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.JobPost.EmployerID, "EmployerID", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.JobPost.EmployerID,
                        (SelectList)ViewBag.EmployerID,
                        Model.JobPost.Employer.Id);
                @Html.ValidationMessageFor(model => model.JobPost.EmployerID)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model=>model.AllJobTags,"JobTag",new {@class="control-label col-md-2"})
            <div class="col-md-10">
                @Html.ListBoxFor(m => m.SelectedJobTags, Model.AllJobTags)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

We can select more than one JobTag by multiselecting, as in the below


After saved, below what we can see in out Index page
Let take a look on the mechanism that it's behind. From the Edit page, when we save a POST command is triggered as below
Note the the query string use the "JobPost.<FieldName>" and that we have multiple SelectedJobTag.
This is important to understand the mechanismo of the MVC autobinder. When we click on Save, the Action
           public ActionResult Edit(JobPostViewModel jobpostView)
from the controller JobStatus is called. MVC5, becuase its ModelBinder, will automatically map the value on the query string to the related property of the class JobPostViewModel injected in the Action. We could override this mechanism for a more complex ViewModel object using the [Bind] decorator with the Action. But this is could be a subject for a new article. I hope I gave you a first idea about what is behind the scene with binding in ASP.NET MVC.

Conclusion:

ASP.NET MVC5 with its Scaffolding mechanism too often has huge limitation in real world application. In this article I tryed to explain you how to use ASP.NET MVC in real world with a simple example about the implementation of a Many to Many relationship.
The example is really a basic one, but I hope that you got the idea behind the Binder and the ViewModel, so you are ready to go alone to the next level starting to modify the "create" feature in the enclosed sample project.
People could think to use other mechanisms like PropertyBag/ViewBag instead of ViewModel for example to pass other data to the View. You will lose the AutoBind mechanism and  it also is definetly not correct from the point of view of S.O.L.I.D. principles, TDD approach and Design Object Oriented in general.

C# : How to Read and Insert Data Using Stored Procedures

Note:This article will show you in a simple manner how to read data from SQL data base by using stored procedures and how to insert data through a stored procedure.

Steps to Read and Insert Data
-------------------------------

Step 1 : Create the table(user_tab) to insert data

CREATE TABLE [dbo].[user_tab](
    [U_name] [varchar](50) NULL,
    [U_pwd] [varchar](50) NULL,
    [U_type] [varchar](10) NULL
)


Step 2 : Create the stored procedure to insert data to user table

 Collapse | Copy Code
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE AddUser
    @name varchar(50),
    @pwd varchar(50),
    @type varchar(10)
AS
BEGIN

    SET NOCOUNT ON;

    insert into user_tab (U_name,U_pwd,U_type)
    values(@name,@pwd,@type)

END
GO


Step 3 :Add windows form

Create a windows form to enter the details which we are going to save in database.

textbox1=> to enter name

textbox2=> to enter password

combobox => to select user type

button(btnSave)=> to save data to database through stored procedure

 Add a class called DBConnect

class DBConnect
    {
        public static SqlConnection myCon = null;

        public void CreateConnection()
        {
            myCon = new SqlConnection("Data Source=GAYANI-PC;Initial Catalog=soft1;Integrated Security=True");
            myCon.Open();

        }
    }


Step 4 : Button click event

Click on button. Then add this code inside that event.

private void btnAdd_Click(object sender, EventArgs e)
        {
            SqlConnection con = DBConnect.myCon;
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "Execute AddUser @name,@pwd,@type";

            cmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = textBox1.Text.ToString();
            cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 50).Value = textBox2.Text.ToString();
            cmd.Parameters.Add("@type", SqlDbType.VarChar, 10).Value = comboBox1.Text.ToString();
           
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
           
        }

You can insert data to the database now ! Check it.



Step 5 : Stored procedure to Read data

GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE ReadUser
   
AS
BEGIN
   
    SET NOCOUNT ON;

    select U_name,U_type from user_tab
END
GO


Step 6 : Read data through Stored procedure(ReadUser) and display on a grid view

public void LoadGrid()
        {
            SqlConnection con = DBConnect.myCon;
            SqlDataReader rd;

            using(con)
            {
                SqlCommand cmd = new SqlCommand("ReadUser",con); // Read user-> stored procedure name
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    dataGridView1.Rows.Add(rd[0].ToString(), rd[1].ToString()); //gridview has 2 columns only(name, type)
                }
                rd.Close();
            }
            con.Close();
        }


Step 7 : Call above method to form load event or any button click event.

private void Form1_Load(object sender, EventArgs e)
        {
            this.LoadGrid();          
        }
 Now you can read and insert data through a stored procedure.