Im making PostHelper.cshtml in App_Code folder inside my Blog project. And I got this error on line:

<div class="commentsTab">
            <a href="@Href("~/Posts/Details/" + **Post.ID + "#comments")">@Post.comments.Count**</a>
</div>

and:

@foreach (tag Tag in **Post.tags**)

when Im deleting "@Post.comments.Count" its fine but Ive got similar line and there's no errors:

<div class="postTitle"><a href="@Href("~/Posts/Details/" + Post.ID)">@Post.Title</a></div>

whats wrong with this? There's whole code:

@using Blog.Models;
@helper Render(post Post, System.Web.Mvc.HtmlHelper html, bool isAdmin, bool showComments)
{
<div class="postTitle"><a href="@Href("~/Posts/Details/" + Post.ID)">@Post.Title</a></div>
<div class="postContainer">
    <div class="postTabs">
        <div class="dateTab">
            <div class="month">@Post.DateTime.ToString("MMM").ToUpper()</div>
            <div class="day">@Post.DateTime.ToString("dd")</div>
        </div>
        <div class="commentsTab">
            <a href="@Href("~/Posts/Details/" + Post.ID + "#comments")">@Post.comments.Count</a>
        </div>
    </div>
    <div class="postContent">
        <div class="postBody">@html.Raw(Post.Body)</div>
        <div class="tagList">
            @foreach (tag Tag in Post.tags)
            {
                <span class="tag"><a href="@Href("~/Posts/Tags/" + Tag.Name)">@Tag.Name</a></span>
            }
        </div>
        <div class="linkList">
            <div id="fb-root"></div>
            <script>
                (function (d, s, id) {
                    var js, fjs = d.getElementsByTagName(s)[0];
                    if (d.getElementById(id)) return;
                    js = d.createElement(s); js.id = id;
                    js.src = "//connect.facebook.net/pl_PL/sdk.js#xfbml=1&version=v2.0";
                    fjs.parentNode.insertBefore(js, fjs);
                }(document, 'script', 'facebook-jssdk'));
            </script>
        </div>
    </div>
</div>
if (showComments)
{
    <div id="commentContainer">
        <a id="comments"></a>
        @foreach (comment Comment in Post.comments.OrderBy(x => x.DateTime))
        {
            <div class="comment">
                <div class="commentName">
                    @if (!string.IsNullOrWhiteSpace(Comment.Email))
                    {
                        <a href="mailto:@Comment.Email">@Comment.Name</a>
                    }
                    else
                    {
                        @Comment.Name;
                    }
                </div>
                said:
                <div class="commentBody">@html.Raw(html.Encode(Comment.Body).Replace("\n", "<br/>"))</div>
                <div class="commentTime">at @Comment.DateTime.ToString("HH:mm") on @Comment.DateTime.ToString("yyyy/MM/dd")</div>
            </div>
        }
        <div id="commentEditor">
            <div id="commentPrompt">Leave a comment!</div>
            <form action="@Href("~/Posts/Comment/" + Post.ID)" method="post">
                <input type="text" id="commentNamePrompt" name="name" /> Name (required)<br />
                <input type="text" id="commentEmailPrompt" name="email" /> Email (optional)<br />
                <textarea id="commentBodyInput" name="body" rows="10" cols="60"></textarea><br />
                <input type="submit" id="commentSubmitInput" name="submit" value="Submit!" />
            </form>
        </div>
    </div>
}

}

My action:

public ActionResult Index(int? id)
    {
        int pageNumber = id ?? 0;
        IEnumerable<post> posts =
            (from Post in model.posts
            where Post.DateTime < DateTime.Now
            orderby Post.DateTime descending
            select Post).Skip(pageNumber * PostsPerPage).Take(PostsPerPage + 1);
        ViewBag.IsPreviousLinkVisible = pageNumber > 0;
        ViewBag.IsNextLinkVisible = posts.Count() > PostsPerPage;
        ViewBag.PageNumber = pageNumber;
        ViewBag.IsAdmin = IsAdmin;
        return View(posts.Take(PostsPerPage));
    }

What is the difference between a repository and a model, and would I want to use both or use one or the other for building my own MVC framework in PHP?

If I have a view controller that contains another view controller, what is the correct way to compose them such that the child view controller will receive all relevant notifications (such as ViewWillAppear)?

If I do the obvious thing in the parent view controller:

this.AddChildViewController(this.childViewController);

I get the expected behavior in the simulator, but not on the device. That is, ViewWillAppear is correctly invoked when running in the simulator, but not when running on the device itself. On the device, I have to resort to hacks such as calling the child controller's ViewWillAppear method from the parent implementation.

EDIT: more info...my ViewWillAppear method on the parent VC is not being called at all on the device (but is on the simulator). WTF?

Viewmodel

public string Personal_Data_Surname { get; set; }
public string FamilyMember_SurName { get; set; }

Entity class Applicant

public string SurName { get; set; }

Entity class FamilyMember

public string SurName { get; set; }

Automapper Config

        Mapper.Configuration.RecognizePrefixes("Personal_Data_");
        Mapper.CreateMap<ApplicationViewModel, Applicant>();

        Mapper.Configuration.RecognizePrefixes("FamilyMember_");
        Mapper.CreateMap<ApplicationViewModel, FamilyMember>();

Controller code mapping entities

Applicant applicant = Mapper.Map<ApplicationViewModel, Applicant>(vaModel);
FamilyMember familyMember = Mapper.Map<ApplicationViewModel, FamilyMember>(vaModel);

The problem is that it maps Personal_Data_Surname from the viewmodel to the Surname in entity class Applicant and FamilyMember. Is it possible to specify a prefix for a specific type

I have this warning

DataTables warning (table id = 'datatabledetail'): Unexpected number of TD elements. Expected 3 and got 0. DataTables does not support rowspan / colspan in the table body, and there must be one cell for each row/column combination.

when my table is empty,

what must I do ??

this my code for datatable

var oTableDetail = $('#datatabledetail').dataTable({
        "bSort": false,
        "bAutoWidth": false,
        "bProcessing": false,
        "bFilter": false,
        "bPaginate": false,
        "aoColumns": [
                        { "mDataProp": "Id", "bVisible": true },
                        { "mDataProp": "CodeValue", "bVisible": true },
                        { "mDataProp": "NameValue", "bVisible": true }
        ]//
        ,
        "aoColumnDefs": [
                            {
                                "fnRender": function (o) {
                                    return "<center>  <input type='button' id='" + o.aData['Id'] + "' class='cremove mws-button blue' value='Remove'></center>";
                                },
                                "aTargets": [0]
                            }
        ]
    });

this my code in html

<table cellpadding="0" cellspacing="0" border="0" class="mws-table" id="datatabledetail"
                               width="100%">
                            <thead>
                                <tr>
                                    <th style="text-align: center; width: 5%;">
                                        Action
                                    </th>
                                    <th style="text-align: center; width: 40%;">
                                        Food Name
                                    </th>
                                    <th style="text-align: center; width: 10%;">
                                        Food Code
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>

                                </tr>
                            </tbody>
                        </table>

I have a Change Password feature on my User Control Panel that is not working. It pick's up values from input and passes them from controller to service, service receives them but when he treys to hit back-end with them the debug console returns: Cannot read property 'protocol' of undefined.

Important: Please refer to my previews question here before you write your solution to understand why I have to use fields of an object to scope input. Pleas consider that sending whole object to backend is not an option, thank you.

Form (.html):

<accordion-group heading="Change password" is-open="changePasswordStatus.open" style="cursor: pointer">
    <div>
        <div>
            <form class="form-horizontal" role="form">
                <form-row model="password.newPassword" name="New: " size="col-sm-8"></form-row>
                <form-row model="password.repeatedNewPassword" name="Repeat: " size="col-sm-8"></form-row>
                <form-row model="password.currentPassword" name="Current: " size="col-sm-8"></form-row>
                <br>
            </form>
        </div>
        <div>
            <button class="btn btn-default btn-sm" data-ng-click="changePassword()">Save</button>
            <button class="btn btn-warning btn-sm" ng-click="changePasswordStatus.open = !changePasswordStatus.open">Cancel</button>
        </div>
    </div>
</accordion-group>

userController.js:

collectionsApp.controller('userController', function($scope, userService, $timeout, $state) {
    $scope.password = {
        newPassword : "",
        repeatedNewPassword : "",
        currentPassword : ""
    }

    $scope.init = function() {
        userService.getCurrentUser(getCurrentUser);
    }

    $scope.changePassword = function() {
        if ($scope.password.newPassword === $scope.password.repeatedNewPassword) {
            userService.changePassword($scope.password.newPassword, $scope.password.currentPassword);
    }
}

...

userService.js:

collectionsApp.service('userService', function($http) {
    return {
        changePassword : function(newPassword, currentPassword) {
            $http.post('/user/changePassword', newPassword, currentPassword);
        }

    };
});

Debug:

enter image description here

Error in console:

enter image description here

What is the best way to set a dynamic body class? Tried:

<body class="@Umbraco.Field("pageTitle", altFieldAlias: "pageName")">

But this returns the page name like:

<body class="Some Page Name">

I have a SwitchesController that inherits from BaseSwitchesController, for the json.

module Api
  module V1
    class SwitchesController < BaseSwitchesController
      respond_to :json
    end
  end
end

I have another SwitchesController, also inheriting from BaseSwitchesController, for the html.

class SwitchesController < BaseSwitchesController
  layout 'application'
end

BaseSwitchesController inherits from ApplicationController.

class BaseSwitchesController < ApplicationController
  def update
    respond_to do |format|
    if @switch.update(switch_params)
      format.html { redirect_to @switch, notice: 'Switch was successfully updated.' }
      format.json { render json: @switch.as_json.merge(:message => 'set_switch_value') }
    else
      format.html { render action: 'edit' }
      format.json { render json: @switch.errors, status: :unprocessable_entity }
    end
  end
end

I want to move the json to the SwitchesController in the API module. The problem is that the methods in SwitchesController are looking for views in views/base_switches, but that folder doesn't exist. It should be looking for views in views/switches, and choose e.g. index.json.rabl.

How can I fix this? Thanks!

How to use Resource file values in javascript asp.net form applications. I have a folder called Resources inside that I have TestResources.resx file. There I want to get ErrorMessage value. I have written below code inside but nothing returned.

var alertValue=@TestResources.ErrorMessage;
alert(alertValue);

net mvc

If created my clas project, projectUser and user

I want to create a projectUser by selecting the id from project and the id from user both in a dropdownList

My projectUser controller

 // GET: /ProjectUser/Create
    public ActionResult Create()
    {
        ViewBag.UserID = new SelectList(db.Users, "Id", "UserName");
        ViewBag.ProjectID = new SelectList(db.Projects, "Id", "ProjectID");
        return View();
    }

    // POST: /ProjectUser/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="ProjectUserID")] ProjectUser projectuser)
    {
        if (ModelState.IsValid)
        {
            db.ProjectUsers.Add(projectuser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.UserID = new SelectList(db.Users, "Id", "UserName", projectuser.User.Id);
        ViewBag.ProjectID = new SelectList(db.Projects, "Id", "ProjectID", projectuser.Projects.ProjectID);
        return View(projectuser);
    }

My view

<div class="form-horizontal">
    <h4>ProjectUser</h4>
    <hr />
    @Html.ValidationSummary(true)
    <div class="form-group">
        @Html.LabelFor(model => model.Projects, "Kies project", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("ProjectID", String.Empty)
            @Html.ValidationMessageFor(model => model.Projects)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.User, "Kies user", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Id", String.Empty)
            @Html.ValidationMessageFor(model => model.User)
        </div>
    </div>

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

my projectUser class

 public class ProjectUser
    {

        public int ProjectUserID { get; set; }
        public virtual ApplicationUser User { get; set; }
        public virtual Project Projects { get; set; }
    } 

I want to use href to call a controller and then display the data in a view. I tested following href and it worked:

<a href="/Samples/Create?id=@Model.ID" class="btn btn-primary btn">Add Sample/a>

However, the id I need to pass is a selected record id that I can get by using Ajax method:

var id = $('[name="RadioRequest"]:checked').prop('id');

The problem is that I can not pass the id to href since the id is not view-level variable.

The question is then: what is the syntax to express this selected (radio button) id inside the href? I tried to copy and paste $('[name="RadioRequest"]:checked').prop('id') into the href to get:

<a href="/Samples/Create?id=$('[name="RadioRequest"]:checked').prop('id')" class="btn btn-primary btn">Add Sample/a>.

It did not work.

I got a page written in c# and a webform written in HTML.

My goal is to show this html webform every time the default.aspx page get loaded ONLY when the cookie are already SET on the client browser. I will set/write the cookie through php from the webform so I assume the c# code just need to:

  1. READ THE COOKIE VALUE IF IS SET OT NOT,
  2. VISUALIZE OR NOT the html webform depending of the value cookie set.

Not sure if this must be done with c# in code behind or just in javascript.

So, is there any code in C# that allow me to call an HTML page and open it in the same page as a webform/pop-up? Also, is possible to trigger this html page in the way I can call it only if cookie are set?

public partial class Read : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["cookie"] != null)
    {
        ReadCookie();
    }
}

protected void ReadCookie()
{
    //Get the cookie name the user entered
    String strCookieName = Request.QueryString["cookie"].ToString();

    //Grab the cookie
    HttpCookie cookie = Request.Cookies[strCookieName];

    //Check to make sure the cookie exists
    if (cookie == null)
    {
        lblCookie.Text = "Cookie not found. <br><hr>";   -> SHOW HTML-WEBFORM 
    }
    else
    {

-> DONT SHOW HTML-WEBFORM 
    }
}
}

This the the code I am using to select/deselect grid view records.This code was working fine until I used the zoom effect and I have to use the zoom effect. `

<script type="text/javascript">
                $("[id*=chkAll]").live("click", function () {
                    var chkHeader = $(this);
                    var grid = $(this).closest("table");
                    $("input[type=checkbox]", grid).each(function () {
                        if (chkHeader.is(":checked")) {
                            $(this).attr("checked", "checked");
                            $("td", $(this).closest("tr")).addClass("selected");
                        } else 


               `{$(this).removeAttr("checked");
                    $("td",$(this).closest("tr")).removeClass("selected");`   

              }
                    });
                });enter code here


                $("[id*=chkDelete]").live("click", function () {
                    var grid = $(this).closest("table");
                    var chkHeader = $("[id*=chkAll]", grid);
                    if (!$(this).is(":checked")) {
                        $("td", $(this).closest("tr")).removeClass("selected");
                        chkHeader.removeAttr("checked");
                    } else {
                        $("td", $(this).closest("tr")).addClass("selected");
                        if ($("[id*=chkDelete]", grid).length == $("[id*=chkDelete]:checked", grid).length) {
                            chkHeader.attr("checked", "checked");
                        }`}` });`

               `</script>`
    `<script type="text/javascript"  src="../js/jquery.zoomooz.min.js"></script>
            <link href="../css/website.css" rel="stylesheet" />`

These are the css and jquery plugin I am using for zoom effect in gridview

I have a problem with my angular routes when entering the URL directly in the URL bar of the browser.

What happens is this. When my app loads up I call a single MVC controller which loads a MVC view which holds inside it a ng-view. This then in turn loads my main angular view. This works great. I then select some options and click save which then routes me to my success view. (Angular takes good care of this). However, when I try to go directly to my success view I get a 404 error returned from the server.

Now I know this is because there isn't a route in MVC that takes care of this for me, but there is a route that should redirect to my main MVC index view which in turn loads up my angular app.

routes.MapRoute(
    name: "Settings",
    url: "{controller}/{*catchall}",
    defaults: new { controller = "Settings", action = "Index" }
);

Now I would expect that when I refresh a page this controller would be called which should load up my angular app where the angular routing takes over and displays the correct view, but this doesn't happen at all.

My angular routes

parts of the URL omitted

angular.module('app', ['ngRoute', 'restangular']).config([
    '$routeProvider', 'RestangularProvider', '$locationProvider', function ($routeProvider, RestangularProvider, $locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
            when('/**/**/**/settings', {
                templateUrl: 'App/globalsettings/templates/globalsettings.html',
                controller: 'globalsettingsCtrl'
            }).
            when('/**/**/**/success', {
                templateUrl: 'App/globalsettings/templates/success.html',
            }).
            when('/**/**/**/error', {
                templateUrl: 'App/globalsettings/templates/error.html',
            }).
            otherwise({ redirectTo: '/**/**/**/settings' });

        RestangularProvider.setBaseUrl("api");
    }
]);

Can anyone answer as to why my routing fails when refreshing the page or entering the URL directly.

When you know id is suppose to exist as in the example below, is it good practice to check for nulls?

var submission = _ctx.Submissions.FirstOrDefault(p => p.Id == id);

submission.Done = true;
_ctx.Submissions.Attach(submission);
_ctx.Entry(submission).State = EntityState.Modified;
_ctx.SaveChanges();

How to validate the text inside a .csv? I want to check the data and don’t save it, if at least 1 line of the file is incorrect.

Example data:

ISPROG3,09-23-14,BATMAN         #correct
ISPROG2,08-23-14,SUPERMAN       #correct
KRISTERKRISTEKRISTER            #wrong

My code:

        try
         { //this determines the type of extension that is only allowed in the fileupload
          string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
          string[] allowedExtenstions = new string[] { ".txt", ".csv"};
          if (allowedExtenstions.Contains(ext))
         { //if the extension is qualified then we proceed with the upload 
             string uploadfile = Server.MapPath("~/Upload/");//create first a folder where we will store the uploaded file
             uploadfile += FileUpload1.FileName;
             if (File.Exists(uploadfile))
             {
                 File.Delete(uploadfile);
             }
             FileUpload1.PostedFile.SaveAs(uploadfile);
             if (File.Exists(uploadfile))
             {
                 using (StreamReader sr = File.OpenText(uploadfile))// we read the file line by line
                 {
                     string inputline = "";
                     while ((inputline = sr.ReadLine()) != null)
                     {
                         string temp = inputline;
                         string name = temp.Substring(0, temp.IndexOf(","));//Name is from the first index [0] until the index of the first comma 
                         temp = temp.Substring(temp.IndexOf(",") + 1);// Only retain the date and feedbacks fields 
                         string date = temp.Substring(0, temp.IndexOf(","));//date is the start of the first index[0] until the index of the first comma
                         temp = temp.Substring(temp.IndexOf(",") + 1);//we cut the date and retain feedbacks
                         string feedbacks = temp;
                         upload.ID = int.Parse(txtID.Text);//it's in the textbox read-only
                         upload.Name = name;//upload.name comes from my business logic layer
                         upload.Date = date;//upload.date comes from my business logic layer
                         upload.Feedbacks = feedbacks;
                         upload.adduploads();//add function to transfer to the database
                         GridView2.DataSource = upload.search();//we view the added value 
                         GridView2.DataBind();

                     }
                 }

             }
         }
         else
         {
             Label39.Text = "NOTEPAD AND CSV FILE ONLY";
         }

        }
        catch (Exception ex)
        {
            Label39.Text = "*" + ex.Message;
       }

I am unable to apply slice or substr to GId due to the following error message:

Uncaught TypeError: Unable to process binding "foreach: function (){return waititem }"
Message: Unable to process binding "style: function (){return { color:GId.slice(0,1) =='TR'?'black':'red'} }"
Message: undefined is not a function 

Html

<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: waititem">
        <tr data-bind="style: { color: GId.slice(0,1) == 'TR'? 'black' : 'red' }">
            <td data-bind="text: PId"></td>
            <td data-bind="text: PName"></td>
        </tr>
    </tbody>
</table>

How can I apply slice to check for the presence of a particular substring and style the row respectively?

In my code I am trying to give Sharepoint a path and a file. Programmatically I want to create any folders that don't already exist and then place my file in the last one.

So with a path like "Example/Test/", I want to check if the "Example" folder exists, if not create it. I have managed to get this working if I have a root folder to go from, but not vice versa.

I frequently get this error with our 5 year old asp.net web application. It seems to be connected with Ajax Control Toolkit as I frequently see this error after upgrading it to a newer version. What is important to me is this error always seems to come from a Google directed request. Not every request by any means, but one or two a day from a Google IP address such as 66.249.67.24.

The redacted request url is http://www.-------.co.uk/default.aspx?_TSM_HiddenField_=ctl00_MainContent_ToolkitScriptManager1_HiddenField&_TSM_CombinedScripts_=%3B%3BAjaxControlToolkit%2C+Version%3D4.1.60919.0%2C+Culture%3Dneutral%2C+PublicKeyToken%3D28f01b0e84b6d53e%3Aen-US%3Aee051b62-9cd6-49a5-87bb-93c07bc43d63%3Af2c8e708%3Ade1feab2%3Af9cec9bc%3Af4fab6f6%3Aca57ef3c

with a message of "An unhandled exception has occurred".

and exception of "System.ArgumentNullException"

I'm running on a Windows 2012r2 and IIS8 server, although this similar error has occurred for a few years now with always the previous Ajax CT version in the query sting and on a Windows 2008 with IIS7. ASP.NET is version 4 framework and error was similar in version 2 and 3.5 in previous years.

In my web.config I have.

<LegacyAccessViolationPolicy enabled="1" />
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="AjaxControlToolkit" publicKeyToken="28f01b0e84b6d53e" />
<bindingRedirect oldVersion="1.0.0.0-4.1.60919.0" newVersion="7.1213" />
</dependentAssembly>
</assemblyBinding>
</runtime>

I believe this should serve up the latest 7.1213 instead of the earlier version requested.

Perhaps the null does not refer to Ajax CT at all.

I'm at a loss how to stop this error, but would be happy to work with anyone and provide more information and run tests to come to a solution. Perhaps I could trap this error by intercepting the request at Application_BeginRequest in Global.asa. Would a simple 304 redirection solve the issue to default.aspx with no query string included Or perhaps a rewrite rule to do the same?

Firstly, I come from a big PHP background with MVC, when I started with PHP, I browsed a lot of times, to try my best and perfect my MVC-Like design in PHP. A lot of people like answered with answers which helped me a lot.

But after starting GUI development in Swing, the answers about MVC in Swing are totally different. For instance, a model is also a view? According to Oracle's Suggestions TextElementModel doesn't have any logical business here, all it does is markup (set color etc) and setting data such as set text and so on. When I developed in PHP, there is no such thing as AbstractModel because I always got told that a model is not a class, or more, it's a whole layer that processes logical business.

In PHP I used Services, Data Mappers and Domain Objects, suggested from this amazing answer which helped me in PHP a lot: How should a model be structured in MVC?

My attempt

After reading again, I thought to give it a go and do a similar thing in Java:

I have the ControllerContainer which creates all controllers:

public class ControllerContainer {

    private JFrame frame;

    public ControllerContainer(JFrame rune) {
        this.frame = frame;
    }

    public void initControllers() {
        Atest test = new Atest(frame);
        test.registerView("test", new ViewTest(test));
    }

}

As you see, I add the view named "test" with instance of ViewTest to the controller, now it will be visible in the frame, and can take input.

My Controller class, which should be abstract, but I didn't make it abstract yet:

public class Controller {

    private JFrame frame;

    private Map<String, Component> views = new HashMap<String, Component>();

    public Controller(JFrame frame) {
        this.frame = frame;
    }

    protected void registerView(String title, Component c) {
        this.views.put(title, c);
        this.frame.add(c);
    }

    protected void deregisterView(String title) {
        this.frame.remove(this.views.get(title));
        this.views.remove(title);
    }

    protected Component getView(String title) {
        return this.views.get(title);
    }
}

And an test controller:

public class Atest extends Controller {

    public Atest(JFrame frame) {
        super(frame);
    }

    public void hit() {
        ((ViewTest) super.getView("test")).changeColorBlue();
    }
}

And my TestView:

public class ViewTest extends JPanel {

    private final Atest controller;

    public ViewTest(Atest c) {
        this.controller = c;
        setBackground(Color.RED);
        setLocation(0,0);
        setSize(300, 300);
        setLayout(null);

        JButton b = new JButton("hello");
        b.setSize(150, 150);
        b.setLocation(0,0);

        b.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                controller.hit();
            }
            @Override
            public void mouseEntered(MouseEvent arg0) {
            }
            @Override
            public void mouseExited(MouseEvent arg0) {
            }
            @Override
            public void mousePressed(MouseEvent arg0) {
            }
            @Override
            public void mouseReleased(MouseEvent arg0) {
            }
        });

        add(b);
    }

    public void changeColorBlue() {
        setBackground(Color.BLUE);
    }

}

The problem

As you see, my view creates a new button, and adds a mouse listener to it. the listener will have access to the controller to pass input. The controller gets the input and changes the view.

Basically the controller instantly forced to update the view, without any serious logical business because it's not needed in my case.

According to the link I have posted above, answered by tereško, how can I use his idea & suggestions with Java Swing correctly?

I am really confused, after the PHP background.

Maybe I am misunderstanding and everything should be done differently in different languages? But I thought that patterns should always be implemented the same way.

If you need more information, let me know.

My MVC is below:

MODEL:

Ext.define('test.model.mdlPerson', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'name' },
        { name: 'surname' }, 
        { name: 'email' }
    ]
}); 

STORE:

Ext.define('test.store.Person', {
    extend: 'Ext.data.ArrayStore',
    model: 'test.model.mdlPerson',
    data: [
        { name: 'Edddd', surname: 'dfasd', email: 'ed@sencha.com' },
        { name: 'Tommy', surname: 'dfgdfgdfg', email: 'tommy@sencha.com' }
    ],
    storeId: 'Person'
});

GridPanel VIEW:

Ext.define('test.view.GridPanel', {
    extend: 'Ext.grid.Panel',
    title: 'The GridPanel',
    alias: 'widget.gridpanel',
    itemId: 'gridPanelId',
    store: 'Person',
    initComponent: function() {
        columns : [
                { text: 'Name', dataIndex: 'name' },
                { text: 'Surname', dataIndex: 'surname' },
                { text: 'E-mail', dataIndex: 'email' }
            ]
        this.callParent(arguments);
    }
});

CONTROLLER:

Ext.define('test.controller.GridPanel', {
    extend: 'Ext.app.Controller',
    stores: ['Person'],
    models: ['mdlPerson'],
    views: ['GridPanel'],
    refs: [{
        ref: 'gridpanel',
        selector: 'gripanel'
    }]
});

The problem is that the store can't be loaded. I have tried also the getStore() method but nothing appears. Anyone help here! Thank you very much!!!