I am building a basic PHP MVC framework that I can duplicate, use, and expand upon for my future projects. My folder layout is as follows:

MVC controllers {controllers here} libs Application.php Controller.php View.php models views error index.php index index.php _templates _header _footer .htaccess index.php

I have no problem with this framework as of now for a basic starting point (note that there are no real pages and content added to this framework at this point). My question deals with folder layout as well as Controller.php class logic. I have seen several basic platforms that seem to do it good have the Controller class looking like this:

    class Controller{
        public function model($model){
            require_once('../app/models/' . $model .'.php');
            return new $model;

        public function view($view, $data= []){
            require_once('../app/views/' . $view . '.php');

In a setup like this, frameworks do not have a View.php class because all of the UI logic that would normally be contained in the View.php class file is just handled in the View method of the Controller.php parent class, with some data passed in. The View method of the Controller.php class does what the View.php class would normally do, and just requires in certain files and renders out the view based off whatever data is in the data array $data [].

While this doesn't seem necessarily bad, it implies that the View.php class is simple enough to just include in the Controller.php class. My question is this, is the View class really that simple that it can just be merged into the Controller.php class? Or should there be more to the View class so that it deserves its own library class? I know there is a lot of debate around the exact purpose of the concept of a view, but I am just wondering if including a view method in the Controller.php class is a bad idea because that tells you you are not using the concept of a View correctly. Both setups seem to work I just see when I have a View.php class it seems I don't have enough to it to justify it having its own class, when it could be simply applied to the Controller.php class.

I would like some basic tips on implemenging a view properly and basically some opinions as to whether it should be merged into a Controller class or not. Thanks!

I have just started learning MVC 5 and the Entity Framework as well as using the Identity Model.

I am trying to add an additional property to the ApplicationUser Model that is a list of Customers. Basically, a user can have many Customers attached to their login.

I seem to have it at least displaying the list of customers on the Register.cshtml page, however I am unsure if this is the best way to do this.

In my RegisterViewModel.cs, I have added the below:

    [Display(Name = "Customer List")]
    public IEnumerable<Customer> Customers { get; set; }

Then in my AccountController, I have added to get a list of customers and pass this to the ViewModel:

    private GatewayContext gatewayContext = new GatewayContext();

    var customers = gatewayContext.Customers.ToList();
    var viewModel = new RegisterViewModel();
    viewModel.Customers = customers;
    return View(viewModel);

Is this the correct way of doing this? My worry is that I have created the gatewayContext as a property of the AccountController and not sure if this is the correct way of going about it.

Sorry if the question is a bit ambigious. I can reword if necessary! I just want to make sure I am building my application in the correct way.

When my view loads, I need to check which domain the user is visiting, and based on the result, reference a different stylesheet and image source for the logo that appears on the page.

This is my code:

    string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];

    if (currentstore == "www.mydomain.com")
        <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
        string imgsrc="/content/images/uploaded/store1_logo.jpg";
        <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
        string imgsrc="/content/images/uploaded/store2_logo.gif";

Then, a little further down I call the imgsrc variable like this:

<a href="@Url.RouteUrl("HomePage")" class="logo"><img  alt="" src="@imgsrc"></a>

I get an error saying:

error CS0103: The name 'imgsrc' does not exist in the current context

I suppose this is because the "imgsrc" variable is defined in a code block which is now closed...?

What is the proper way to reference this variable further down the page?

I need to render a partial view in a view using ajax, but not in page load. I want render this partial when a drop value was changed. This partial should have a model and load a jsTree from model information. When I searched for a solution I found following code.

        url: '/Home/Details',
        contentType: 'application/html; charset=utf-8',
        type: 'GET',
        dataType: 'html'

    }).success(function (result) {
$('#sectionContents').html(result);}).error(function (xhr, status) {

But I need to render a partial with its own model. This code gets html result which generates after a view will be rendered. Can anybody help please?

I'm new to .net and I'm trying to use Razor but i don't get it. For example:

@if (price>30)                  //C#
{                               //C#
<p>The price is too high.</p>   //html
}                               //C#
else                            //C#
{                               //C#
<p>The price is OK.</p>         //html
}                               //C#

This is so confusing. Any rules to follow? Please help.

I have a lengthy form which I have broken to several parts and am using @Html.EditorFor for each section which is working great but need your thoughts on whether this approach can be improved or not.

There are Segments and Every Segment can have Multiple Activities, So I have a Collection of Segments and every Segment in this collection contains a Collection of Activities.

    public class Activity
        public string ActivityId { get; set; }
        public string ActivityDescription { get; set; }
        public bool IsSelected { get; set; }
    public class Segment
        public string SegmentId { get; set; }
        public string SegmentDescription { get; set; }
        public List<Activity> Activitites { get; set; }

This was how I wanted the ViewModel that I use as a model for the view should look like but couldn't make it to work since @Html.EditorFor didn't accept a Collection Type.

    public class UserPreferencesViewModel
       //..... Other Properties
       public List<Segment> Segments {get; set;}

Here is the ViewModel

@model UserPreferencesViewModel
   //... Other Properties
   @Html.EditorFor(m => m.Segments) //I assigned Segments three Segments in the Controller Get Method

Here is the EditorFor Template for Segments

@model List<Segment>
   //... Other Properties
   @foreach(var segment in Model)
      //Do the stuff

But this doesn't work saying EditorFor cannot take collections and the exception is thrown at RunTime.

Here is my work Around. I created another Class "UglySegmentWorkAround" which contains the Segment Collection and then in the UserPreferencesViewModel I removed the List Property and instead defined a property for that.

public class UglySegmentWorkAround
public List<Segment> Segments {get; set;}

public class UserPreferencesViewModel
           //..... Other Properties
           public UglySegmentWorkAround UglySegmentWorkAround {get; set;}

and Here is the EditorFor Template.

@model UglySegmentWorkAround
       //... Other Properties
       @foreach(var segments in Model.Segments)
          //Do the stuff

It works perfectly but I just don't feel comfortable with this approach, is there anything I am missing in the first approach? How this should be done? I don't want the EditorFor to do an implicit loop if I Pass it a collection because I am rendering a complex UI structure in the EditorFor and I need the EditorFor to have the loop inside it.

We have an asp.net web forms application. In the application we want to add a feature that would allow enduser to enter first name or last name and the control should be able to bring all the available users in active directory matching with the firstname or last name and display it to enduser to for selection. Once the enduser selects the username I would like to save user information in my local database.

I was wondering if I could get some help on how to make call to active directory and what user control should I use in aspx page.

The following code worked until I moved to Asp.net Framework 4.5.

        var dateAndPort = (from c in context.CruiseCalendar
                        where c.ShipId == sourceId
                        && c.CruiseDayDate >= dateRange.Start
                        && c.CruiseDayDate <= dateRange.End
                        select new DateAndPort
                            Date = c.CruiseDayDate,
                            DestinationId = c.ListingId

        var shipRendezvous = (from r in context.CruiseCalendar
                             where (dateAndPort.Any(d => d.Date == r.CruiseDayDate
                             && d.DestinationId == r.ListingId))
                             select r).GroupBy(x => x.CruiseDayDate) //Groups by date
                            .Where(x => x.Count() >= shipCount) // if shipCount for dateAndPort > 0 only rendezvous will be returned
                            .SelectMany(x => x)
                            .OrderBy(r => r.CruiseDayDate)

          return shipRendezvous;

Now this throws an error when executing the second query (var shipRendezvous = ). The error is in full:

Unable to cast the type 'System.Linq.IQueryable1[[Seven.Domain.CustomTypes.DateAndPort, Seven.Domain, Version=, Culture=neutral, PublicKeyToken=null]]' to type 'System.Data.Entity.Core.Objects.ObjectQuery1[[Seven.Domain.CustomTypes.DateAndPort, Seven.Domain, Version=, Culture=neutral, PublicKeyToken=null]]'. LINQ to Entities only supports casting EDM primitive or enumeration types.

Any ideas whats going on? regards, Guy

(I affixed the first query with a .ToList() and now get this error: Unable to create a constant value of type 'Seven.Domain.CustomTypes.DateAndPort'. Only primitive types or enumeration types are supported in this context.)

I am new to Rails, ORM and database building. I am currently building a 2 sided marketplace platform like AirBnb, but I am not quite sure how to lay out the relationships between the models properly for this type of platform, like one_to_many rel or such.

Here is what I wish to achieve.

Customer can signup, create an account/login/profile -> User Table

Customer can generate a request/order, such as, food order, cleaning order, etc -->??

the other gets displayed to service workers, who fits the criteria for the order, if the worker is a cook, then he/she gets to see all of the orders related to food order, sorted by cost, requirement, etc.

I am not really sure how to map out the association of these 3 models... Can anyone help me?

I found this on MSDN, which seems to suggest I can do it in the following way:

        <deny verbs="OPTIONS" users="*" />

But when I test this using cURL, it appears to be available still:

curl -v -X OPTIONS https://mySite.com
< HTTP/1.1 200 OK
* Server Microsoft-IIS/7.5 is not blacklisted
< Server: Microsoft-IIS/7.5
< X-Powered-By: ASP.NET
< Access-Control-Allow-Methods: POST, DELETE
< Access-Control-Allow-Headers: x-requested-with, cache-control, content-type
< Date: Fri, 26 Sep 2014 15:43:18 GMT
< Content-Length: 0

What is the proper way to block the OPTIONS http method?

I'm essentially trying to disable all RequiredFieldValidators on a page using the function ValidatorValidate(id, boolean) however my first step would be to get a collection of all the validators on the page and then filter them down to just the RequiredFieldValidators.

I'd like to do this using javascript only if possible.

Hi Everyone. I am using the jquery.treeview.js in my ASP.Net Website. I am trying to Expand the selected note after redirect to another page. i.e


When I choose an Parent Node (item1) the website redirects to item1 and set the nose as selected. What Iam trying to achieve is to expand item1 after redirect.

Thanks in advance.

I have created a map location with Google maps. The first time when I type address, zipcode, state, or city, it works fine. second time it does not. Also, when the input box is empty and i click search it fails. Here is my code. can anyone find the problem. I tried debugging but no luck.


<asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="btnSearch(); return false;" cssClass="form-control" />


function btnSearch() {
    var addressBox = document.getElementById('address').value;
    if (addressBox == "") {
        return false;

    var radius = document.getElementById('radiusSelect').value;
    var address = document.getElementById('address').value;

    geocoder.geocode({ 'address': address }, function (results, status) {
        var variable = results[0].geometry.location;
        var next = [variable.lat(), variable.lng()];
        $.post("FindPhysician.aspx?lat=" + variable.lat() + "&lng=" + variable.lng() + "&radius=" + radius, function () {
            if (status == google.maps.GeocoderStatus.OK) {
                var mapOptions =
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.ROADMAPW,
                    center: results[0].geometry.location,
                map = new google.maps.Map(document.getElementById('map'), mapOptions);

                currentLocation = results[0].formatted_address;
                currentLocation = encodeURIComponent(currentLocation.trim());

                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    animation: google.maps.Animation.DROP,
                    title: "<div style='width:auto;height:35px;'>" + results[0].formatted_address,
                    icon: 'images/pin-blue.png'
                //google.maps.event.addListener(marker, "click", function (e) {
                var infoWindow = new google.maps.InfoWindow({
                    position: results[0].geometry.location,
                    content: marker.title,
                infoWindow.open(map, marker);
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.open(map, marker);

I've been running experiments with HAProxy's reconfiguration and am seeing some results I don't fully understand.

I'm running HAProxy on CentOS and am sending it requests from Windows 7. For the reconfiguration, I'm using "haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid)".

I ran two experiments:

1) A console application in Windows is running in a loop, spawning a new webclient each iteration, and sending a request to HAProxy. While the loop is running, I do a hot reconfig. --> this results in the reconfig being blocked until the console application is closed (bad).

2) A console application in Windows is running in a loop, sending a request to an ASP.NET website. The ASP.NET website on each page load sends a request to HAProxy. While the loop is running, I do a hot reconfig. --> this results in the reconfig swapping almost immediately (good).

I think that ASP.NET connection pooling is to blame in the connection staying open in the first experiment, but I was wondering if someone could explain to me exactly what's happening.

Hey i have to edit a software that was not made by me, therefore i dont have the project file for Visual Studio.

The problem is there i want to add some fields to a search field but i cant access the code. ![enter image description here][1]

As you can see the aspx.cs file is loaded with codebehind, and i sucesfuly traced the file to a dll in the project. With the help of a program called .net refletor i opened the dll and "peek" the code. but i cant Save! How do i edit the code ?


I have two div and they have some width. But I want each div to take full space as it's given in width property regardless of the content inside div s. Currently each div is taking space with respect to the content inside them and ignoring what is given in width property.

My HTML is given below,

  <div style="margin-left:100px; display:inline;  border-width:10px; width:30%; border-     style:solid;">
<div style=" margin-left:10px;  display:inline; border-width:10px; width:30%; border-style:solid">ali</div>

  • I am trying to use plupload-2.1.2 in asp.net application. So to start with I downloaded this plugin from the below URL. http://www.plupload.com/download/

    • Unzipped the folder on C drive and opened this below file.


    • I made sure I have silverlight and flash plugin installed.

    • When I open this page it shows. "Your browser doesn't have Flash, Silverlight or HTML5 support."

    • But when I go to the plupload website I can see the user interface which is used for uploading file.

    • I tested this on IE 10 and latest firefox. Both shows same error but when you browse plupload website it works fine.

So I have 3 tabs at the top of form they are contained in <div>s. Here is the CSS:

.lefttab1 {

    position: relative;
    border-top-right-radius: 50px;
    -webkit-box-shadow: 2px -1px 2px #CCC;
    height: 35px;
    width: 300px;
    float: left;
    margin-top: 44px;
    padding-top: 10px;


.midtab {
    position: relative;   
    border-top-right-radius: 50px;
    -webkit-box-shadow: 2px -1px 2px #CCC;
    height: 35px;
    width: 400px;
    margin-top: 44px;
    margin-left: 259px;
    padding-top: 10px;

.righttab1 {

    border-top-right-radius: 50px;
    height: 35px;
    width: 375px;
    float: right;
    margin-top: -45px;
    padding-top: 10px;


Here is the markup:

<a href="/account.aspx" class="lefttab1 tabcolorGrey">
                 <asp:Label ID="lablelft" runat="server" ForeColor="#a1a1a1" text="Select A Payment Account" CssClass="tabtextLeft1"></asp:Label>
            <div class="midtab tabcolorGrey">
                 <asp:Label ID="Label3" runat="server" ForeColor="#a1a1a1" text="Payment Information" CssClass="tabtextLeft1"></asp:Label>
            <div class="righttab1 tabcolorPurple">
                 <asp:Label ID="Label4" runat="server" ForeColor="#ffffff" text="Payment Confirmation" CssClass="tabtextRight1"></asp:Label>

So, Lefttab1 needs to overlay midtab, and midtab should overlay righttab1. Right now it appears that Lefttab1 is NOT overlaying midtab, but midtab is overlaying righttab1. What can I do, I have tried manipulating the postion: attribute, and I have tried the z-index, but nothing seems to work. Any advice would be appreciated. Regards,

I want to display different pictures in my content section depending on the hour of the day. The if-statement is working fine, its just the delivering of the variable (which contains the URL to the files) into an external javascript which is bugging me. And it needs to be an external file because its too big to include it into the main file. This javascript handles the hilighting of the usemap areas of the picture.

This is my SiteLayout.cshtml which also displays the content later on:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charset="utf-8" />
    <link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <script type="text/javascript">mapUrlElement</script> <--- tried to define the variable up front (didnt work)
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.10.3.js"></script>
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
    <script src="~/Scripts/jquery.maphilight.js"></script> <--- the javascript in question
    <meta name="viewport" content="width=device-width" />

Thats were the content will be rendered

<div id="body">
        @RenderSection("featured", required: false)
        <section class="content-wrapper main-content clear-fix">

Now the content file default.cshtml

Layout = "~/_SiteLayout.cshtml";
Page.Title = "XXXXXXXXXXX";

private String mapUrl;   <--- definition so it can be accessed throughout the whole file

if(@DateTime.Now.Hour > 6 && @DateTime.Now.Hour <= 8){
    mapUrl = "";
else if (@DateTime.Now.Hour > 8 && @DateTime.Now.Hour <= 10){
    mapUrl = "~/Images/thondorfMapt.png";
else if (@DateTime.Now.Hour > 10 && @DateTime.Now.Hour <= 12){
    mapUrl = "~/Images/thondorf.jpg";
<input hidden id="url" value="@mapUrl"/> <--- one try to pass it as a value (didnt work)

<script type="text/javascript">

$(function () {    <---- the function in question
    urlElement = document.getElementById("url");  <--- getting the content of the input (no effect)
    mapUrlElement = urlElement.value;

   @* window.mapUrl = "@mapUrl";      @*... wird noch getestet ...*@

    $('img[usemap]').maphilight();    <---- this is working fine without the variable URL

<img width="1420" class="map" src="@mapUrl" usemap="#thondorfLayout" id="thondorf" />

And finally the section in the maphilight.js which should display the picture as background of a canvas it created

wrap = $('<div></div>').css({
            background:'url("'+this.src+'")', <--- thats were the mapUrlElement should be inserted, but i have no clue HOW !? (tried several ways)
            zIndex: '1'

cheers fellows .. i hope there is a solution for this peculiar problem ;)

I have a form to manage the insertion of comments:

@model GatorsWebSite.Comment
  @using (Html.BeginForm("Create", "Comments", FormMethod.Post, new { enctype = "multipart/form-data" }))
    @Html.HiddenFor(m => m.ArticleID)
    @Html.TextAreaFor(m => m.Text, new { @class = "form-control wide", @placeholder = "Type your comment", @rows = "3" })
    @Html.ValidationMessageFor(m => m.Text, "", new { @class = "text-danger" })

This is the action on controller:

public ActionResult Create([Bind(Include = "Text, ArticleID")] Comment comment){
  if (comment == null || comment.ArticleID <= 0)
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

  if (ModelState.IsValid){
    comment.Date = DateTime.Now;
    comment.UserID = User.Identity.GetUserId();
  return RedirectToAction("Details", "News", new { ID = comment.ArticleID });

Since the action is under authorization, if the user is not logged in

    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl){
      if (ModelState.IsValid){
        var user = await UserManager.FindAsync(model.UserName, model.Password);
        if (user != null){
          await SignInAsync(user, model.RememberMe);
          return RedirectToLocal(returnUrl);
          ModelState.AddModelError("", "Invalid username or password.");
      return View(model);

enter image description here

enter image description here

the redirect url will be Comments/Create and will fail with a 404 error, does exist a general solution to manage this problem, since I cannot use a simple redirect to action?

Hi thank you all for assisting me. I am very new to ASP.net MVC and EF and am playing around to do some real project. I would really appreciate if someone could please guide me of how I can insert data into two tables in SQL with one to many relationships. I have a requirement where I need to add multiple families to one behavior case.

  • tblCase [case_id] [case_no]
  • tblFamily [family_id] [first_name] [last_name] [case_id]

After following an online tutorial I am able to add multiple families but I can not get my head around how to:

  1. Add a new case -> retrieve the last inserted case_id
  2. Add all the families with the last inserted case_id in one submit button click.

My view looks like the following:

@model List<TestMVC.Family>

ViewBag.Title = "BulkData";
Layout = "~/Views/Shared/_Layout.cshtml";

td {
   padding: 5px;
<div style="width:700px; padding:5px; background-color:white;">
@using (Html.BeginForm("BulkData", "Save", FormMethod.Post))

   if (ViewBag.Message != null)
       <div style="border:solid 1px green">

    <div id="dvCase">
               <td>Case Name</td>
               <td><input type="text" value="" /></td>
               <td>Case No</td>
               <td><input type="text" value="" /></td>

   <div><a href="#" id="addNew">Add New</a></div>
   <table id="dataTable" border="0" cellpadding="0" cellspacing="0">
           <th>First Name</th>
           <th>Last Name</th>
           <th>Case Id</th>
       @if (Model != null && Model.Count > 0)
           int j = 0;
           foreach (var i in Model)
               <tr style="border:1px solid black">
                   <td>@Html.TextBoxFor(a => a[j].firstName)</td>
                   <td>@Html.TextBoxFor(a => a[j].lastName)</td>
                   <td>@Html.TextBoxFor(a => a[j].case_id)</td>
                       @if (j > 0)
                           <a href="#" class="remove">Remove</a>

   <input type="submit" value="Save" />

and my controller looks like :

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

namespace TestMVC.Controllers
 public class SaveController : Controller
   // GET: /Save/
   public ActionResult BulkData()
       // This is only for show by default one row for insert data to the database
       List<Family> ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id= 0 } };
       return View(ci);

   public ActionResult BulkData(List<Family> ci)
       if (ModelState.IsValid)
           using (FamilyContext dc = new FamilyContext())
               foreach (var i in ci)
                ViewBag.Message = "Data successfully saved!";
                ci = new List<Family> { new Family { family_id = 0, firstName = "", lastName = "", case_id = 0 } };
       return View(ci);