What is MVC(Model view controller)?
Can you explain the complete flow of MVC?
Is MVC suitable for both windows and web application?
What are the benefits of using MVC?
Is MVC different from a 3 layered architecture?
What is the latest version of MVC?
What is the difference between each version of MVC?
What are routing in MVC?
Where is the route mapping code written?
Can we map multiple URL’s to the same action?
How can we navigate from one view to other view using hyperlink?
How can we restrict MVC actions to be invoked only by GET or POST?
How can we maintain session in MVC?
What is the difference between tempdata,viewdata and viewbag?
What are partial views in MVC?
How did you create partial view and consume the same?
How can we do validations in MVC?
Can we display all errors in one go?
How can we enable data annotation validation on client side?
What is razor in MVC?
Why razor when we already had ASPX?
So which is a better fit Razor or ASPX?
How can you do authentication and authorization in MVC?
How to implement windows authentication for MVC?
How do you implement forms authentication in MVC?
How to implement Ajax in MVC?
What kind of events can be tracked in AJAX?
What is the difference between “ActionResult” and “ViewResult”?
What are the different types of results in MVC?
What are “ActionFilters”in MVC?
Can we create our custom view engine using MVC?
How to send result back in JSON format in MVC?
What is “WebAPI”?
But WCF SOAP also does the same thing, so how does “WebAPI” differ?
With WCF also you can implement REST,So why "WebAPI"?
How can we detect that a MVC controller is called by POST or GET?
Disclaimer
What is MVC(Model view controller)?
- The “View” is responsible for look and feel.
- “Model” represents the real world object and provides data to the “View”.
- The “Controller” is responsible to take the end user request and load the appropriate “Model” and “View”.
Can you explain the complete flow of MVC?
- All end user requests are first sent to the controller.
- The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
- The final view is then attached with the model data and sent as a response to the end user on the browser.
Is MVC suitable for both windows and web application?
What are the benefits of using MVC?
Is MVC different from a 3 layered architecture?
| Functionality | 3 layered / tiered architecture | Model view controller architecture |
| Look and Feel | User interface. | View. |
| UI logic | User interface. | Controller |
| Business logic /validations | Middle layer | Model. |
| Request is first sent to | User interface | Controller. |
| Accessing data | Data access layer. | Data access layer. |
What is the latest version of MVC?
What is the difference between each version of MVC?
| MVC 2 | MVC 3 | MVC 4 |
| Client-Side Validation Templated Helpers Areas Asynchronous ControllersHtml.ValidationSummary Helper Method DefaultValueAttribute in Action-Method Parameters Binding Binary Data with Model Binders DataAnnotations Attributes Model-Validator Providers New RequireHttpsAttribute Action Filter Templated Helpers Display Model-Level Errors | RazorReadymade project templates HTML 5 enabled templatesSupport for Multiple View EnginesJavaScript and Ajax Model Validation Improvements | ASP.NET Web APIRefreshed and modernized default project templatesNew mobile project template Many new features to support mobile apps Enhanced support for asynchronous methods |
What are routing in MVC?
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
Where is the route mapping code written?
Can we map multiple URL’s to the same action?
How can we navigate from one view to other view using hyperlink?
<%= Html.ActionLink("Home","Gotohome") %>
How can we restrict MVC actions to be invoked only by GET or POST?
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
How can we maintain session in MVC?
What is the difference between tempdata ,viewdata and viewbag?
| Maintains data between | ViewData/ViewBag | TempData | Hidden fields | Session |
| Controller to Controller | No | Yes | No | Yes |
| Controller to View | Yes | No | No | Yes |
| View to Controller | No | No | Yes | Yes |
What are partial views in MVC?
How did you create partial view and consume the same?
<body> <div> <% Html.RenderPartial("MyView"); %> </div> </body>
How can we do validations in MVC?
public class Customer { [Required(ErrorMessage="Customer code is required")] public string CustomerCode { set; get; } }
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post)) { %> <%=Html.TextBoxFor(m => m.CustomerCode)%> <%=Html.ValidationMessageFor(m => m.CustomerCode)%> <input type="submit" value="Submit customer data" /> <%}%>
public ActionResult PostCustomer(Customer obj) { if (ModelState.IsValid) { obj.Save(); return View("Thanks"); } else { return View("Customer"); } }
Can we display all errors in one go?
<%= Html.ValidationSummary() %>
[StringLength(160)] public string FirstName { get; set; }
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }
[Range(10,25)]public int Age { get; set; }
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
TryUpdateModel(NewCustomer);
ModelState.AddModelError("FirstName", "This is my server-side error.");
How can we enable data annotation validation on client side?
<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script> <script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script> <script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>
<% Html.EnableClientValidation(); %>
What is razor in MVC?
Why razor when we already had ASPX?
<%=DateTime.Now%>
@DateTime.Now
So which is a better fit Razor or ASPX?
How can you do authentication and authorization in MVC?
How to implement windows authentication for MVC?
<authentication mode="Windows"/> <authorization> <deny users="?"/> </authorization>
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")] public class StartController : Controller { // // GET: /Start/ [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")] public ActionResult Index() { return View("MyView"); } }
How do you implement forms authentication in MVC?
<authentication mode="Forms"> <forms loginUrl="~/Home/Login" timeout="2880"/> </authentication>
public ActionResult Login() { if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123")) { FormsAuthentication.SetAuthCookie("Shiv",true); return View("About"); } else { return View("Index"); } }
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}
How to implement Ajax in MVC?
- Ajax libraries
- Jquery
<script language="javascript"> function OnSuccess(data1) { // Do something here } </script> <div> <% var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"}; %> <% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %> <input id="txtCustomerCode" type="text" /><br /> <input id="txtCustomerName" type="text" /><br /> <input id="Submit2" type="submit" value="submit"/></div> <%} %>
<span id="DateDiv" /> <%: Ajax.ActionLink("Get Date","GetDate", new AjaxOptions {UpdateTargetId = "DateDiv" }) %>
public class Default1Controller : Controller { public string GetDate() { Thread.Sleep(10000); return DateTime.Now.ToString(); } }
function GetData()
{
var url = "/MyAjax/getCustomer";
$.post(url, function (data)
{
$("#txtCustomerCode").val(data.CustomerCode);
$("#txtCustomerName").val(data.CustomerName);
}
)
}
What kind of events can be tracked in AJAX?
What is the difference between “ActionResult” and “ViewResult”?
public ActionResult DynamicView() { if (IsHtmlView) return View(); // returns simple ViewResult else return Json(); // returns JsonResult view }
What are the different types of results in MVC?
Note: -It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are “ActionResult”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest.
- ViewResult - Renders a specified view to the response stream
- PartialViewResult - Renders a specified partial view to the response stream
- EmptyResult - An empty response is returned
- RedirectResult - Performs an HTTP redirection to a specified URL
- RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
- JsonResult - Serializes a given ViewData object to JSON format
- JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
- ContentResult - Writes content to the response stream without requiring a view
- FileContentResult - Returns a file to the client
- FileStreamResult - Returns a file to the client, which is provided by a Stream
- FilePathResult - Returns a file to the client
What are “ActionFilters”in MVC?
- Implement post-processinglogicbeforethe action happens.
- Cancel a current execution.
- Inspect the returned value.
- Provide extra data to the action.
- Inline action filter.
- Creating an “ActionFilter” attribute.
public class Default1Controller : Controller , IActionFilter { public ActionResult Index(Customer obj) { return View(obj); } void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) { Trace.WriteLine("Action Executed"); } void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { Trace.WriteLine("Action is executing"); } }
public class MyActionAttribute : ActionFilterAttribute , IActionFilter { void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) { Trace.WriteLine("Action Executed"); } void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { Trace.WriteLine("Action executing"); } }
[MyActionAttribute] public class Default1Controller : Controller { public ActionResult Index(Customer obj) { return View(obj); } }
Can we create our custom view engine using MVC?
public class MyCustomView : IView { private string _FolderPath; // Define where our views are stored public string FolderPath { get { return _FolderPath; } set { _FolderPath = value; } } public void Render(ViewContext viewContext, System.IO.TextWriter writer) { // Parsing logic <dateTime> // read the view file string strFileData = File.ReadAllText(_FolderPath); // we need to and replace <datetime> datetime.now value string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString()); // this replaced data has to sent for display writer.Write(strFinal); } }
public class MyViewEngineProvider : VirtualPathProviderViewEngine { // We will create the object of Mycustome view public MyViewEngineProvider() // constructor { // Define the location of the View file this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview" }; //location and extension of our views } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath); MyCustomView obj = new MyCustomView(); // Custom view engine class obj.FolderPath = physicalpath; // set the path where the views will be stored return obj; // returned this view paresing logic so that it can be registered in the view engine collection } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath); MyCustomView obj = new MyCustomView(); // Custom view engine class obj.FolderPath = physicalpath; // set the path where the views will be stored return obj; // returned this view paresing logic so that it can be registered in the view engine collection } }
protected void Application_Start() { // Step3 :- register this object in the view engine collection ViewEngines.Engines.Add(new MyViewEngineProvider()); <span class="Apple-tab-span" style="white-space: pre; "> </span>….. }
How to send result back in JSON format in MVC?
public JsonResult getCustomer() { Customer obj = new Customer(); obj.CustomerCode = "1001"; obj.CustomerName = "Shiv"; return Json(obj,JsonRequestBehavior.AllowGet); }
What is “WebAPI”?
But WCF SOAP also does the same thing, so how does “WebAPI” differ?
| SOAP | WEB API | |
| Size | Heavy weight because of complicated WSDL structure. | Light weight, only the necessary information is transferred. |
| Protocol | Independent of protocols. | Only for HTTP protocol |
| Formats | To parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call. | Output of “WebAPI” are simple string message,JSON,Simple XML format etc. So writing parsing logic for the same in very easy. |
| Principles | SOAP follows WS-* specification. | WEB API follows REST principles. (Please refer about REST in WCF chapter). |
With WCF also you can implement REST,So why "WebAPI"?
How to implement “WebAPI” in MVC?
public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } }
How can we detect that a MVC controller is called by POST or GET?
public ActionResult SomeAction() { if (Request.HttpMethod == "POST") { return View("SomePage"); } else { return View("SomeOtherPage"); } }
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam