Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts

Wednesday, August 15, 2018

How to Upload Files in ASP.NET MVC

 Upload Files In ASP.NET MVC
Here i am going to explain File Upload example in ASP.Net MVC  
 Below code is quite limited and simple functionality for single file upload, and it will work in any browser.  
 Before uploading the file, we will check whether Directory exists if not exist then the Directory will be created.  
 View  
 View consists of an HTML form containing the submite button, which open a select file dialog, and Submit, which sends the chosen file to  
 the server in a POST request.  
 <html>  
 <head>  
   <meta name="viewport" content="width=device-width"/>  
   <title>Index</title>  
 </head>  
 <body>  
   <div>  
     @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
     {  
       <span>Select File:</span>  
       <input type="file" name="postedFile"/>  
       <hr/>  
       <input type="submit" value="Upload"/>  
       <br/>  
       <span style="color:green">@ViewBag.Message</span>  
     }  
   </div>  
 </body>  
 </html>  
 Controller  
 public class HomeController : Controller  
 {  
   // GET: Home  
   [HttpGet]  
   public ActionResult Index()  
   {  
     return View();  
   }   
   [HttpPost]  
   public ActionResult Index(HttpPostedFileBase postedFile)  
   {  
     if (postedFile != null)  
     {  
       string path = Server.MapPath("~/Upload/");  
       if (!Directory.Exists(path))  
       {  
         Directory.CreateDirectory(path);  
       }   
       postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));  
       ViewBag.Message = "File uploaded successfully.";  
     }   
     return View();  
   }  
 }  

JQ GRID in ASP.NET MVC 4 using Razor

 JQ GRID Using MVC with Razor View Engine in ASP.NET MVC 4  
 Friends,Here i am going to explain how to use jqgrid in asp.net mvc4 with rzor view engine.JQGrid is one of the most flexible and stable
 gird you can find in the current tech market. It’s free to use. Here i am going to write basic step to do where data will come from 
database to show in JQgrid.  
 Following are step by step sequence to create the JQGRID.  
 1.Create a new ASP.NET MVC 4 Web Project  
 2.Select Empty template with Razor   
 4.Right Click on the Controller and Add new Controller  
 5.Copy and paste the below code in the controller as fllowing  
 using System;  
 using System.Collections.Generic;  
 using System.Web;  
 using System.Web.Mvc;  
 using System.Data;  
 using System.Data.SqlClient;  
 using System.Configuration;  
 using JQGridExample.Models;  
 namespace JQGridExample.Controllers  
 {  
   public class EMPLOYEEController : Controller  
   {  
     public ActionResult EmpDetails()  
     {  
       return View();  
     }  
     public JsonResult getEmpDetails()  
     {  
       List<Employee> items = new List<Employee>();  
       items = getData();  
       var a = Json(items, JsonRequestBehavior.AllowGet);  
       a.MaxJsonLength = int.MaxValue;  
       return a;  
     }  
     public List<Employee> getEmpData()  
     {  
       string connString = ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString;  
       SqlConnection conn = new SqlConnection(connString);  
       SqlCommand cmd = new SqlCommand();  
       cmd.CommandTimeout = 6000;  
       cmd.CommandText = "select * from employee";  
       cmd.Connection = conn;  
       conn.Open();  
       DataTable dataTable = new DataTable();  
       SqlDataAdapter da = new SqlDataAdapter(cmd);  
       da.Fill(dataTable);  
       conn.Close();  
       da.Dispose();  
       List<Employee> items = new List<Employee>();  
       foreach (DataRow row in dataTable.Rows)  
       {  
         items.Add(new MEmployee  
         {  
           Id = row["ID"].ToString(),  
           Name = row["Name"].ToString(),  
           Gender = row["Gender"].ToString(),  
           Contact = row["Contact"].ToString(),  
           Address = row["Address"].ToString(),  
           State = row["State"].ToString(),  
                          Country = row["Country"].ToString()  
         });  
       }  
       return items;  
     }  
   }  
 }  
 6.Add new class to the Model folder and paste the below code in the Model.  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 namespace JQGridExample.Models  
 {  
   public class Employee  
   {  
     public string Id { get; set; }  
     public string NAME { get; set; }  
     public string Name { get; set; }  
     public string Gender { get; set; }  
     public string Contact { get; set; }  
     public string Address { get; set; }  
           public string State { get; set; }  
           public string Country { get; set; }  
   }  
 }  
 8. Right Click on the Controller and Add the View ,name should be EmpDetails  
 9. Add below code to the created EmpDetails view  
 @{  
   ViewBag.Title = "JQGrid Esample";  
 }  
 <html>  
 <head>  
   <title>My First JQGrid Example</title>  
 <script src="~/Scripts/jquery-1.11.0.min.js"></script>  
 <link href="yourlocalpath/ajax/libs/jqueryui/1.8.13/themes/base/jquery-ui.css" rel="stylesheet" />  
 <script src="yourlocalpath/jqgrid/4.6.0/jquery.jqGrid.min.js"></script>  
 <script src="yourlocalpath/jqgrid/4.6.0/i18n/grid.locale-en.js"></script>  
 <script src="yourlocalpath/jqgrid/4.6.0/jquery.jqGrid.min.js"></script>  
 <link href="yourlocalpath/jqgrid/4.6.0/css/ui.jqgrid.css" rel="stylesheet" />  
   <style type="text/css">  
     .ui-jqgrid .ui-widget-header {  
       background-color: #336699;  
       background-image: none;  
       color: white;  
     }  
     .ui-jqgrid .ui-jqgrid-labels th.ui-th-column {  
       background-color: #FFCC66;  
       background-image: none;  
       color: #336699;  
       height: 30px;  
       font-weight: bold;  
     }  
   </style>  
   <script type="text/javascript">  
     $(function () {  
       $("#myEmpGrid").jqGrid({  
         url: '@Url.Action("getEmpDetails")',  
         datatype: 'json',  
         mytype: 'get',  
         colNames: ['Id','Name', 'Gender', 'Contact', 'Address', 'State','Country'],  
         colModel: [  
 { name:'Id', width:'35px' },  
 { name:'Name', width:'160px' },  
 { name:'GENDER' },  
 { name:'Gender' },  
 { name:'Address' },  
 { name:'State'},  
 { name:'Country'}  
               ],  
         pager: $('#myPager'),  
         rowNum: 5,  
         sortname: 'ID',  
         gridview: true,  
         sortorder: 'desc',  
         loadonce: true,  
         rowList: [5, 10, 20, 50],  
         width: 600,  
         height: 110,  
         viewrecords: true,  
         caption: 'Emp details in JQ Grid'  
       });  
     });  
   </script>  
 </head>  
 <body>  
   <div>  
     <table id="myEmpGrid"></table>  
     <div id="myPager"></div>  
   </div>  
 </body>  
 </html>  
 Run your application and test   

Thursday, August 10, 2017

ASP.NET MVC interview questions & answers

What is MVC (Model View Controller)?
Answer: 
MVC is an architectural pattern which separates the UI and Data Model and business logic. It’s divided into three parts, Model, View, and Controller.

1. The Model represents the data and pass it to view (Database objects).
2. The View displays the data and responsible for look and feel of the page (from database).
3. The Controller handles the user input(request) and load appropriate model and view.

What are the advantages of MVC?
Answer: 
Multi view support
Due to the separation of the model from the view, the user interface can display multiple views of the same data at the same time.

Separation of Concerns
Separation of Concerns is one of the core advantages of ASP.NET MVC .Since code-behind concept has been removed from MVC
The MVC framework provides a clean separate logic for the UI, Business Logic, Model or Data.This feature enable code re-usability.
Read More...

Q.Explain “page lifecycle” of an ASP.NET MVC?
When a page is requested first following process are performed by ASP.Net MVC 
Step 1: Routing
In traditional ASP.NET webform application each asp.net page implements the IHTTPHandler interface.
This interface has a ProcessRequest() method that gets called when you request the page. The ProcessRequest() method is responsible for processing the request and generating the response. So in asp.net application it is simple, you request for a page in the url like http://mylocalsite1\default.aspx and then it search for that page on the local disk and execute the processrequest method and generate the html response.
However in MVC application ,request response process is different from webform. In MVC there are no physical page exist for a particular request. All the requests are routed to a special class called Controller. The controller is responsible for generating the response and sending the content back to the browser.
When you build a MVC application you can define a bunch of controllers. Each controller can handle multiple requests. For example, all the following will route to same Controller.
http://mylocalsite1/Controller1/2
http://mylocalsite1/Controller1/3


Question 4: What are different return types of a controller action method?Answer: There are total nine return types we can use to return results from controller to view. The base type of all these result types is ActionResult.
  1. ViewResult (View): View Result is used to return a webpage from an action method.
  2. PartialviewResult (Partialview): PartialViewResult is used to send a part of a view which will be rendered in another view.
  3. RedirectResult (Redirect)RedirectResult is used to redirect to any other controller and action method depending on the URL.
  4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used when we want to redirect to any other action method.
Read More...

Question 5 : What are action filters in aspnet mvc?
Answer : ASP.NET MVC provides a very clean way of injecting the pre-processing and post-processing logic for actions and controllers. We can put the pre-processing and post-processing logic is by decorating the actions with attributes which will invoke an attribute class implementing  the filter's logic.
Read More...