Monday 8 February 2016

What are the different types of results in MVC

Action Result Return type
In the following list we can see the action result type



1.   ViewResult :  This basically render a specific View for the response stream. The View result basically is a class which is inherited by the abstract class of the “ ViewResultBase”, and it is used to render a view. This “ViewResultBase” class contains the methods for finding the specific view for rendering  and also for execution the results. It also contain the properties for indentifying the view to rendering for the application.
public ViewResult Index()
{
    return
 View("ViewResult");  // here It is returning a  View
}

2.   PartialViewResult :- This class also inherited from the abstract base class “ ViewResultBase” class and  it is used to rendering a partial view. This class contains the methods from finding the partial view for rendering and also for the execution of the result. This also contains the properties of  identify the partial view to rendering the application. This is not  like action result. Basically  Partial views are not like the primary thing for display the user which is the view.
public PartialViewResult Index()
{
    return
 PartialView("PartialViewData");
}

3.   RedirectResult: - It is used to perform the HTTP redirect to a given URL from user side. This class is inherited from the Action result abstract class.
public ActionResult Index()
{
    return
 Redirect("http://www.google.com/");
public
 RedirectResult Index1()
{
    return
 Redirect("http://www.google.com/");
}

4.    RedirectToRouteResult :-  This is used to redirect  using specified route data dictionary. This class is inherited from the ActionResult class.
public ActionResult Index(int? Id)
{
    return
 new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Home", action = "List", Id = new int?() }));
}

5.   ContentResult : -  this is used to return an action plain text this is also inherited from actionResult  abstract class.
public ActionResult Index()
{
    return
 Content("Hello");
public
 ContentResult ContentResultIndex()
{
    return
 Content("Hello");
}

6.   JsonResult : -  Action method on controllers basically return the JsonResult means (JavaScript Object Notation result) which can be used in AJAX application. This class inherited from the ActionResult abstract class. Here Json is provided one argument which must be serializable. 
public JsonResult Index()
{
    return
 Json("Hello My Friend!");
}

ActionResult
Helper Method
Description
ViewResult
View
Renders a view as a web page
PartialViewResult
PartialView
Section of a view,that can be rendered inside another view
RedirectResult
Redirect
Redirect to another action method
RedirectToRouteResult
RedirectToRoute
Redirect to another action method
ContentResult
Content
Returns a user-defined content type
JsonResult
Json
Retuns a serialized JSON object
JavaScriptResult
JavaScript
Returns a script that can be executed on the client
FileResult
File
Returns a binary output to write to the response
EmptyResult
(None)
returns a null result

Wednesday 4 November 2015

Important Validation using jquery

1)   Phone number validation using jquery

<html>
<head>
//Import jquery.Min.js
    <script type="text/javascript">
        $.fn.isPhoneNumber = function (options) {
            intRegex = /^[0-9]{1,10}$/;
            phoneNumber = this.val();
            if ((phoneNumber.length != 10) || (!intRegex.test(phoneNumber))) {
                this.val("");
                this.attr("placeholder", "Invalid Phone Number");
                return false;
            }
            return true;
        };

        function validate() {
            $("#checkPhoneNumber").isPhoneNumber(this);
            return false;
        }    </script>
</head>
<body>
    <input type="text" id="checkPhoneNumber" value="ASDFG77" />
    <input type="button" onclick="return validate()"  value="Validate"/>
</body>
</html>


2)   Postal code validation

<html>
<head>
//Import jquery.Min.js
    <script type="text/javascript">

        $.fn.isPostalCodeNumber = function (options) {
            intRegex = /^[0-9]{1,4}$/;
           postalcodeNumber = this.val();
            if ((postalcodeNumber.length != 10) || (!intRegex.test(postalcodeNumber))) {
                this.val("");
                this.attr("placeholder", "Invalid Postal Code Number");
                return false;
            }
            return true;
        };
        function validate() {
            $("#checkPostalCodeNumber").isPostalCodeNumber(this);
            return false;
        }
    </script>
</head>
<body>
    <input type="text" id="checkPostalCodeNumber" value="ASDFG77" />
    <input type="button" onclick="return validate()"  value="Validate"/>
</body>
</html>



3)   English validation

<html>
<head>
//Import jquery.Min.js
    <script type="text/javascript">
     var englishAlphabetAndWhiteSpace = /^[a-zA-Z ]*$/;
        if(!englishAlphabetAndWhiteSpace.test(this.val()))        
  {                this.val("");
                this.attr("placeholder", "Invalid English Alphabets");
                return false;
            }
            return true;
        };
        function validate() {
            $("#checkEnglishAlphabets").isEnglishAlphabets(this);
            return false;
        }
    </script>
</head>
<body>
    <input type="text" id="checkEnglishAlphabets" value="ASDFG77" />
    <input type="button" onclick="return validate()"  value="Validate"/>
</body>
</html>



4)   Get  the selected value form drop down

<html>
<head>
  //Import jquery.Min.js
</head>
<body>
    <select id="countries">
        <option value="1">India</option>
        <option value="2">China</option>
        <option value="3">Russia</option>
        <option value="4">Srilanka</option>
        <option value="5">Pakistan</option>
    </select>
    <input type="button" onclick="return getSelected()" value="Get Selected Value" />
    <script type="text/javascript">
    function getSelected() {
        alert($("#countries option:selected").text());
        alert($("#countries").val());
        return false;
    }
    </script>
</body>
</html>



Saturday 26 September 2015

Display image in asp.net MVC

Here we will learn that how to display image in asp.net mvc.
Step(1):-  Go to Sql Server management system and execute following script.
create database MVCVariousAttribute

use MVCVariousAttribute

Create table Student
(
 Id int primary key identity,
 FullName nvarchar(100),
 Gender nvarchar(10),
 Age int,
 AdmissionDate DateTime,
 EmailAddress nvarchar(100),
 WinningPrize int,
 PersonalWebSite nvarchar(100)
)

Insert into Student values
('Munesh Sharma''Male', 25, '2005-05-05 16:53:36.975''Munesh@gmail.com', 45000,'http://dotnet-munesh.blogspot.in/')

Insert into Student values
('Rahul Sharma', NULL, 30, '2006-06-06 17:42:25.865''Rahul@gmail.com', 35000,'http://dotnet-munesh.blogspot.in/')

Alter table Student Add Photo nvarchar(100), AlternateText nvarchar(100)

Update Student set Photo='~/Photos/Munesh.png',
AlternateText = 'munesh Photo' where Id = 1

Step(2):- Go to Visual studio and add a new project  -> Select “Asp.Net MVC4  Web Application” and give the name for this ,In my case it is “MVCDemoProject
” -> Select a Project template as Empty and View engine is “Razor”, Then Click OK
Step(3):-  Add “EntityFramework dll”  to reference folder in your project if you don’t have then install it through nugget package manager for more go this Go here.

Step(4):- Right click on Model folder and add “Ado.net entity Data Model” and give the name it as “StudentDataModel”, Then click on Add



Step(5): .   When You will click Add button here you will see another window for  “EntityData modal Wizard” from there you select “Generate From DataBase”, And Click Next.
Give the connection name and select your database then click on next



Step(6) .   In this screen select your Database Tables and give Modal Name then click FINISH Button.


When you will click on finish button it will create Student Entity.



Step(6) .  Right click on your project and add a folder with name is “Photos” and put a image in this folder. Download the following image and paste in "Photos" folder. 

Step(7). Add a partial class to this Model folder of this project with the name of student. And put the following code to this class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;

namespace MVCDemoProject.Models
{
    [MetadataType(typeof(StudentMetaData))]
    public partial class Student
    {
    }

    public class StudentMetaData
    {
        #region dataType attribute

        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }

        [ReadOnly(true)]
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }


        [DataType(DataType.Currency)]
        public int? WinningPrize { get; set; }

        // Generate a hyperlink
        [DataType(DataType.Url)]
        [UIHint("OpenInNewWindow")]
        public string PersonalWebSite { get; set; }


        [DataType(DataType.Date)]
        public DateTime? AdmissionDate { get; set; }


        #endregion
}

}


Now right click on controller and a controller with the name is “Home” and put the following code in detail action method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDemoProject.Models;

namespace MVCDemoProject.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Home/Details/5



        public ActionResult Details(int id)
        {
            MVCVariousAttributeEntities _context = new MVCVariousAttributeEntities();
            Student _studentDetail = _context.Students.Where(c => c.Id == id).SingleOrDefault();
            return View(_studentDetail);
        }

        //
        // GET: /Home/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Home/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Home/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Home/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Home/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Home/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}




Step(8):- Next step is that add a view for detail action method so right click on this method -> add view -> Scaffold template as Detail


Step(9) At this position if you go to the following URL then it will not show you the image so for that we need to change in auto generate code in detail view.

http://localhost:3831/Home/Details/1

View Code is
@model MVCDemoProject.Models.Student

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Student</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.FullName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FullName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Gender)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Age)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Age)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.AdmissionDate)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.AdmissionDate)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.EmailAddress)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.EmailAddress)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.WinningPrize)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.WinningPrize)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.PersonalWebSite)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.PersonalWebSite)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Photo)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Photo)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.AlternateText)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.AlternateText)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>



Replace the above marking code with the following code
<div class="display-label">
    @Html.DisplayNameFor(model => model.Photo)
</div>
<div class="display-field">
    <img src="@Url.Content(@Model.Photo)" alt="@Model.AlternateText" />

</div>

we are using Url.Content() html helper method. This method resolves a url for a resource when we pass it the relative path.
Now run your application and output will be

http://localhost:3831/Home/Details/1




Customize HTML helper in asp.net mvc
We are making image tag, by passing values of  "src" and "alt" attributes. Like following

<img src="@Url.Content(@Model.Photo)" alt="@Model.AlternateText" />

 Here if we want to create own HTML helper through that method we can pass image and alt text only using with that our view will not look complicated.MVC doesn’t have image() html helper so we can create it  which accept image and alt text, like following
@Html.Image(Model.Photo, Model.AlternateText)

Basically HTML helper return a string ,like for generating a text box we use following code
@Html.TextBox("TextBox Name")

So, here TextBox() is an extension method defined in HtmlHelper class. In the above code, Html is the property of the View, which returns an instance of the HtmlHelper class.

now add, Image() extension method, to HtmlHelper class. 
1. Right click on MVCDemoProject  application and add a  "CustomHtmlHelpers" folder. 

2. Again Right click on "CustomHtmlHelpers" folder and add a with the name "CustomHtmlHelpers.cs".
3. Write the following code. TagBuilder class is available in System.Web.Mvc namespace.

namespace MVCDemoProject.CustomHtmlHelpers
{
public static class CustomHtmlHelpers
{
    public static IHtmlString Image(this HtmlHelper helper, string src, string alt)

    {
        // Build <img> tag

        TagBuilder tb = new TagBuilder("img");

        // Add "src" attribute

        tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));

        // Add "alt" attribute

        tb.Attributes.Add("alt", alt);

        // return MvcHtmlString. This class implements IHtmlString

        // interface. IHtmlStrings will not be html encoded.
        return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));

    }
}
}


To use the custom Image() html helper in Details.cshtml view, then include the following using statement in “Details.cshtml

@using MVCDemo.CustomHtmlHelpers;


As we intend to use this Image() html helper, in all our views, let's include"MVCDemo.CustomHtmlHelpers" namespace in web.config. This eliminates the need to include the namespace, in every view.

<system.web.webPages.razor>
  
<pages pageBaseType="System.Web.Mvc.WebViewPage">
    
<namespaces>
      
<add namespace="System.Web.Mvc" />
      
<add namespace="System.Web.Mvc.Ajax" />
      
<add namespace="System.Web.Mvc.Html" />
      
<add namespace="System.Web.Routing" />
      
<add namespace="MVCDemo.CustomHtmlHelpers" />
    </namespaces
>
  </pages>

  <host ....../>

</system.web.webPages.razor>



If you intend to use the Image() custom html helper, only with a set of views, then, include a web.config file in the specific views folder, and then specify the namespace in it. 

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...