-->

Wednesday, June 8, 2016

Save and Retrieve Image into database table in ASP.NET MVC

According to my previous article, Which is written in web form. If you are a web form user then try this article. In this article i will show you, How to save image file into database table using ASP.NET MVC, also retrieve image from table to ASP.NET MVC Application. You know that image file saved in the form binary array. So, First to create a table, in which you can take varbinary(max) type field. I will give you an example of simple table.

CREATE TABLE [dbo].[Brand] (
    [BrandId]    INT             IDENTITY (1, 1) NOT NULL,
    [BrandImage] VARBINARY (MAX) NULL,
    PRIMARY KEY CLUSTERED ([BrandId] ASC)
);



Now, Add a EDMX file to prepare a DataContext as well as model. Now, open a HomeController.cs file to write the code for save file. In this file first to pass model in the view. Add a file control in the view file.




@using (Html.BeginForm("AddImage", "Home", FormMethod.Post, new {enctype="multipart/form-data"}))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Brand</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.BrandImage, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" id="image1" name="image1"/>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Submit" class="btn btn-default" />
            </div>
        </div>
    </div>
}

Save file using controller file 

public ActionResult AddImage(Brand model, HttpPostedFileBase image1)
        {
            var db = new Database1Entities3();
            if (image1!=null)
            {
                model.BrandImage = new byte[image1.ContentLength];
                image1.InputStream.Read(model.BrandImage, 0, image1.ContentLength);
                
            }
            db.Brands.Add(model);
            db.SaveChanges();
            return View(model);
        }


Show Image using controller file 

 public ActionResult ShowImage()
        {
            Database1Entities3 db = new Database1Entities3();
            var item = (from d in db.Brands
                        select d).ToList();

            return View(item);
        }
ShowImage View section

@model IEnumerable<WebApplication1.Brand>

@{
    ViewBag.Title = "ShowImage";
}

<h2>ShowImage</h2>
<table>
    <tr>
        @foreach (var item in Model)
        {
        <td>



            @{
            var base64 = Convert.ToBase64String(item.BrandImage);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
            }
            <img src='@imgSrc' style="max-width:100px; max-height:100px;" />
        </td>
        }


    </tr>
</table>

Thursday, May 26, 2016

Anti Xss in ASP.NET MVC

In this ASP.NET MVC Video tutorial i will show you, How to prevent your page from XSS attack. XSS stands for Cross side Scripting attack. Suppose you open your banking website, also open forgery website in other tabs, that sites attack on your banking website also steal your credential information. So, if you are developer then prevent your web page from XSS attacks. Lets see this video:


Friday, April 29, 2016

Similar to TextChanged Event in ASP.NET MVC

This is very good article for web form users who want to get value on TextChanged Event. I mean to say that  TextChanged Event occurs when we move one textbox to another using "Tab" key. When, Web form users moves to MVC projects. He/ She faces some problems in logics. Because, in MVC, For each request we must to call controller. I have an idea to remove such task. I prefer JQuery. So first to Add a ViewModel Class into your project. You can take this sample.

1. Add a new Folder in your project, name of the folder is "viewModel". Now, add a class, which name as addition like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication27.viewModel
{
    public class addition
    {
        public int FirstNumer { get; set; }
        public int SecondNumber { get; set; }
        public int result { get; set; }
    }
}

In this we have three public property.Now, Add a controller class in Controller folder. Like that.

using System.Web.Mvc;

namespace WebApplication27.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            return View();
        }
    }
}

Add View, By using Right click on Action method name. In View section, i will add code of JQuery. You can see

@model WebApplication27.viewModel.addition

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using(Html.BeginForm())
{
    @Html.TextBoxFor(m=>Model.FirstNumer)
    @Html.TextBoxFor(m=>Model.SecondNumber)
    @Html.TextBoxFor(m => Model.result)
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
    $(function () {
        $("#SecondNumber").blur(function () {
            $("#result").val(parseInt($("#FirstNumer").val()) + parseInt($("#SecondNumber").val()))
        });
    })
</script>

Monday, April 18, 2016

Design ASP.NET MVC form using ViewModel class

Welcome, user. Today i would like to share something about Forms and their control like TextBox, Label, DropdownList(SelectListItem), Radio Button etc in ASP.NET MVC. Before going to details, first to share something about ViewModel.
 A ViewModel is a temporary class file which is used to store data values in properties.   
First to take fields which are used in form like UserName, Password, Email, Gender, religions etc. Because we will need controls for each fields. Lets take an simple example. Create a new MVC project.

  1. Right click on your project, Add a new Directory which name should have ViewModel
  2. Add this class file inside the ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MvcApplication1.ViewModel
{
    public class FormVM
    {
        public int Id { get; set; }
        public String UserName { get; set; }
        public String Password { get; set; }
        public String Gender { get; set; }
        public String Religion { get; set; }
        public String Image { get; set; }

        
        public bool IsSubmitted { get; set; }

    }
}

According to the ViewModel class we will take Two TextBox for UserName and Password, Three radio button for Religion, one file control for Image, one DropdownList for Gender and last One Submit control.After add this file, come to controller part. Add a new controller like this.

using MvcApplication1.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class TutorialController : Controller
    {
       public ActionResult AddUser()
        {
            FormVM viewModel = new FormVM();
            viewModel.IsSubmitted = false;
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult AddUser(FormVM model, HttpPostedFileBase file)
        {
            model.IsSubmitted = true;
            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                model.Image = pic;
            }
            ViewBag.Values = model.UserName + ", " + model.Password + ", " + model.Gender + ", " + model.Religion + ", " + model.Image;
            return View(model);
        }

    }
}

By above mentioned code AddUser( ) method return a ViewModel class. Also set IsSubmitted property to false. So using ViewModel class you can create a model control into your view class. So i have a view class for you where your control designed. Let see.

@model MvcApplication1.ViewModel.FormVM

@{
    ViewBag.Title = "AddUser";
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem
    {
        Text = "Male",
        Value = "Male",
        Selected = true
    });
    listItems.Add(new SelectListItem
    {
        Text = "Female",
        Value = "Female"
    });
    listItems.Add(new SelectListItem
    {
        Text = "None",
        Value = "None"
    });
}



<h2>AddUser</h2>

@using (Html.BeginForm("AddUser","Tutorial",FormMethod.Post, new { enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>FormVM</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
           @Html.DropDownListFor(model => model.Gender, listItems, "  Select Gender  ")
        </div>
        <br />
        <div class="editor-label">
            @Html.LabelFor(model => model.Religion)
        </div>
        <br />
        <div class="editor-field">
            @Html.RadioButtonFor(model => model.Religion, "Hindu", new { id = "rbHindu" })
            @Html.Label("Hindu")
            @Html.RadioButtonFor(model => model.Religion, "Muslim", new { id = "rbMuslim" })
            @Html.Label("Muslim")
            @Html.RadioButtonFor(model => model.Religion, "Other", new { id = "rbOther" })
            @Html.Label("Other")
        </div>
        <br/>
        <div class="editor-label">
            @Html.LabelFor(model => model.Image)
        </div>
        <div class="editor-field">
            <input type="file" name="file" id="file" style="width: 100%;" />
            
        </div>

        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}

<div>
    @if(Model.IsSubmitted){
        <p>@ViewBag.Values</p>
    }
</div>

Crate form control according to above mentioned code. When we click on Submit button then value of all control will display on paragraph using ViewBag variable. Now code generate the following output:

Design ASP.NET MVC form using ViewModel class

Tuesday, April 5, 2016

How to show image from database table in ASP.NET MVC

In this article i will show you, How to display image from database in ASP.NET MVC. To do this task, we will use <img /> tag in view section. First of all, Create a connection with the database using Entity Data model (Learn How to use ADO.NET Entity Data Model). In the controller action method pass the list of data to the view. Like that:

 
 private DatabaseEntities db = new DatabaseEntities();

        // GET: Home
        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

In the View section: 

@model IEnumerable<WebApplication23.Employee>

@foreach (Employee item in Model)
{
<img src="@Url.Content(item.Database_Picture_column)" width="100" height="100" />

}

Sunday, March 6, 2016

How to retrieve records from database table in MVC

In this article i will show you, How to retrieve record from database table in MVC. This things we have already learned in ASP.NET WEB FORMS, Now the same things we can do in MVC. Before doing this task first to install Entity Framework in the application. Create a Empty MVC project. Add a new database also create table by using this video tutorial. We have a database table with their following fields:

CREATE TABLE [dbo].[Student_Table] (
    [Id]   INT           IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (50) NULL,
    [City] NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Now, Following these steps to retrieve items from table:

Step-1 :  Create a "Student" model class in model folder. Like :

using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication19.Models
{
    [Table("Student_Table")]
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
    }
}

By using the Table class we can mapped our class to database table. 

Step-2 : Create a "StudentContext" class in model folder. Like

using System.Data.Entity;

namespace WebApplication19.Models
{
    public class StudentContext : DbContext
    {
        public DbSet<Student> students { get; set; }
    }
}

By using "students" property we can communicate with the table.

Step-3 : Create ConnectionString in the Web.Config file, in this way :

<connectionStrings>

    <add name="StudentContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
 
here we have a connection name is same as Context Class name.

Step-4 : Now, add a controller in the Controller folder, copy this code under controller action method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication19.Models;

namespace WebApplication19.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            StudentContext sc = new StudentContext();
            Student singlestu = sc.students.Single(stu => stu.Id == 2);
            return View(singlestu);
        }
    }
}

By using the LINQ Query we have to retrieving student details from table who's id is 2. Now, Build the project. Add a View By Right click on Index Action method.Now, appear a screen look like this.

How to retrieve records from database table in MVC

Fill all mentioned fields, according to mentioned snaps. Now, last
Step-5 : Design to view for values.

@model WebApplication19.Models.Student

@{
    ViewBag.Title = "Student";
}

<h2>Single Student Record</h2>
<div>
    Student Id : @Model.Id <br/>
    Student Name : @Model.Name <br/>
    Student City : @Model.City

</div>

Code Generates the following output:
How to retrieve records from database table in MVC


© Copyright 2013 Computer Programming | All Right Reserved