Extjs MVC - setting up store events in controller - model-view-controller

I have a requirement in my application where in I need to show the UI components(like text field, combo box) based on the values i get from the server side. To be precise, I have a combobox on the page, when the user changes the values i need to send the selected value to server to get information on what needs to be displayed. Without using MVC i implemented it as below
When the user changes the value in the combobox, i refresh(using load method) another store
When i get the data back from the server('datachanged' event) i read the data and create the UI components
Now I am trying to use ExtJS MVC, so i have two questions
How do I access a store which is associated to a controller but not necessarily to any UI components from the view
How can I setup the events of a store in the controller(in the control function) just like we setup events from view
Code i want to setup events from Store like 'datachanged' in controller like below -
this.control({
'viewport > #content-panel' : {
render : this.createMainTabs
}
});

In addition to sha's reply I can say that you may setup your store eventhandlers in your controller. For example you have a combobox with a store, so you could write like this:
this.control({
'#myCombo' : {
afterrender : this.setupStoreListeners
}
});
....
setupStoreListeners: function(combo){
var store = combo.store;
store.on('datachanged', //.....);
}
And one more thing, as sha wrote you could always get store by name, but I use this only when I need to share a store instance between multiple controllers. If I need this store only in one controller, I just save it inside this controller:
setupController: function(){
this.myStore = this.getCombo().store; // now you could use this.myStore anywhere you need
}

To get store object in the controller just use this.getStore('StoreName'), each store by default has its own instance and it doesn't really matter whether it's binded to any UI component you have.
After you get store object you can subscribe to any store events using any method you prefer. I usually like
store.on('load', {...})
Also I would not change anything in UI from the view code. I would put all this customization into controller code.

Related

using ajax or not when displaying new records in asp.net mvc

I am a beginner in MVC. In my application, I list categories (as a button) on the left hand-side (inside a div). Just right to this div, there is another div which displays the items associated with the clicked category.
When a category button is clicked, I am planning to call the action of the controller that will retrieve the Items from the database and add these Items to the ViewModel (e.g., model.Items = db.Items...), and then call the View with the updated Model and display the Items.
However, I am curios if it is better to make an Ajax call here and use a partial view for displaying the Items of the clicked category.
If feel like between these two approaches in my scenario only difference will be the page-refresh, they should work the same in terms of speed since both of them require the same database call.
Can anyone share good practices in MVC for such scenarios?
Yes AJAX is faster and good way to update detail in same page without refresh.
For that you have to create JsonResult method in controller. It will give you result in Json.
Try JQuery Template plugin for repeated code.
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
{{each $data}}
<td>${Col}</td>
{{/each}}
</tr>
</script>
<table id="containerTable">
</table>
AJAX Call
$.ajax({
url: 'Your JsonResult Method URL',
type: "GET",
data: data,
beforeSend: function () {
},
success: function (data) {
// It will pass data to template and template will bind parsing json
$('#trTemplate').tmpl(data).appendTo('#containerTable');
//Business logic
},
complete: function () {
// Your Code
}
});
Your JsonResult Method
[HttpPost]
public JsonResult GetData(ViewModel model)
{
// Your Code here
}
using ajax or not when displaying new records in asp.net mvc
Using jquery would be the best approach for this scenario. As you don't have to load the layout page which will have to render the scripts and stuff all over again. Stick on to Ajax calls in MVC as much as possible, The technologies are being improved and a lot of single page applications are out there, And if we still use a page load for every new request then there is no point.
Coming to comparison between passing back Partial View And Json Data. Which is better to use in the application design?
Both partial Views and Json data hold the same weight depending on the scenario.
When to use partial view: Lets say you have a Model and you have to build the view HTML by lot of if checks and loops and possibly some c# code ( in rare scenarios), etc, in such scenario using Partial view would be the better choice, Because if we try to build the same thing in Jquery using json data the complexity of the code required would be high compared to what can be done in Partial views, But still achieving it is possible but wont be that easy and we might make errors during development.
When to use Json Data: If the requirement is like updating a grid, generating dynamic drop down or dealing with some Jquery plugins in the page I think Json data would be better, as many plugins play with json data as the core requirement.
A Small Example Of Deciding Between Partial View And Json Data - interested folks and read through
Lets take a scenario where we have to display a grid of data. This is our initial requirement. So we can happily build our viewModel with data and pass it to our partial view and render the table using for loops. All set, Now the requirement changes and we are asked to build sorting, filtering and paging stuff in our table. So at present we look for a plugin that can be easily integrated with current code and yes the easy one to use at this scenario is Datatables. Ok, we wrote a small Jquery to apply the plugin to the table and all set we have the fancy stuff ready.
Now here is the tricky part, we are asked to add functionalities like add, edit, delete record from the table. Yes its possible but is little tricky to get it done in the best possible way with the current code which we have. What we tend to do is, when ever there is a change in the table we plan to recall the partial view. Which works fine but still asking to ourselves just to delete one record from the table is it good to reload the partial view again?? Definitely NOT,
What can we do? When ever there is any add, edit, delete operation we hit the controller to update the database and we can make the controller return a JSON data and just pass this Json data to the plugin API and refresh the table, This will be more neat and faster. So here you see JSON data would be the better choice. Also some might even want to make it more cleaner by just playing with that one record of data and writing up some jquery code to manipulate the table, which is absolutely fine, But it requires us to pass the Json data itself back from controller.
So having this done, we can go back and refactor our code to make partial view to use json data for the grid initially too or leave it as it is saying the initial load will be a partial view, but following operations would be a json result, which is fine but I feel let all the data related stuff come from one point.
So that explains how a simple module can change from being a partial view to then use Json data. There are scenarios where the story is the other way around, You have to pick the right one for the right work.

Get Uploader UI elements in onValidate (jQuery S3 Plugin)

During the "validate" event, I'm attempting to gain access to the different UI elements within uploader.
As of right now, I only see private methods attached to the this context. Almost all of them are "private".
In the qq.Templating object within fine-uploader I see: getDropProcessing, etc which are the exact methods I need.
Are these exposed anywhere in the event handler, or on the object where I can access them without knowing the exact classes name? Or is there a way to access the selectorClasses object?
Example of what I'm trying to accomplish:
onValidate: function(imgData, btnContainer){
// "this" context is the qq.s3.fineUploader object created.
var uploader = $(this._options.element), // uploader element
processingEl = uploader.fineUploader('getDropProcessing'); // does not exist.
}
To gain access to a file item and its children in Fine Uploader UI, use the getItemByFileId API method. All other elements are represented in your template, so you should be able to select them using whatever class/attribute/ID you have assigned them in your template.

Knockout JS, MVC 3 and View Model Server Side Data as JSON

So I have a problem...I am separating concerns in my web app: HTML in razor pages and JS in js files. My problem lies in the fact that I want to use data from my controller passed down in the view model from the server as the options of a select list. The problem lies in the fact that I have separated my js from my HTML and I can't access Razor inside the js files.
I have a list of items coming down into my view model...
public List Stuffs { get; set; }
I json encode it server side and make sure to take care of circular refrences, so it looks like this
[{"id":1,"name":"blah"},{"id":2,"name":"blah2"},{"id":3,"name":"blah3"},{"id":4,"name":"blah4"}]
The problem is, I want to keep my separation of concerns, so how do I get that array into my js file so I can bind it to a select list using knockout? I definitely don't want to do another round trip to the server.
So lets say you have some view that looks like this:
<div> (Some stuff) </div>
<script type="text/javascript">
var initialData = //Your JSON
<script>
And then in your javascript (which you have linked below your view, so that it loads after it), you have something like this:
var data = initialData || {} //Or some other default value, in case initialData wasn't set
This will load in the initialData if it was set, or use nothing (or a default your define) if it wasn't. Loosely coupled.
Of course, more complex data will require you to standardize the strucure, but this is essentially one method that allows you to pull in data from the razor generated View without tightly coupling it to your javascript file.
Does your Javascript file contain a view model in the form of an instantiable function, e.g. something like:
function MasterVM(data)
or an object literal, e.g.
var masterVM = { ...
? I tend to go for instantiable view models (partly because they chain down through a hierarchy of view models using the mapping plugin - the top level one builds its children) and that being the case I think it's nice for the Razor view to instantiate the view model with the JSON rendered from the MVC view model, e.g.:
var masterVM = new MasterVM(#(Html.Raw(JsonConvert.SerializeObject(Model.ProductViewModel))));
Or even have the Knockout view model "owned" by a revealing module and initialise it like:
productModule.init(#(Html.Raw(JsonConvert.SerializeObject(Model.ProductViewModel))));
Then productModule is also responsible for other things like mediating between your view model(s) and the server, watching for dirty state, etc.
Also, doing another round trip to the server is not necessarily bad if you are sourcing a massive set of reusable options which you'd like the browser to cache. If you are, you might want to have an MVC controller which emits a big object literal containing all of your commonly used options, which you can then use as the "options" property across multiple selects. But if your options are specific to the particular view model, then I guess they have to be part of your view model.

MVC3 Finding a control by its Name

I have a C#.Net web app and I am trying to access one of the HTML/ASP Text Boxes in the Controller for the Edit View of my Proposal model. In a non-MVC app, I was able to do this using Control.ControlCollection.Find(). Is there an equivalent for a MVC3 project?
You ask for an equivalent of Control.ControlCollection.Find() in MVC?
In MVC your controller is not aware of controls.
The controller just receives data via parameters and returns data via the function result.
What do you want to do with the control in your controller code?
If you want to access the value, you should bind it to a parameter:
View:
<input name="MyControl" type="text" />
Controller:
public ActionResult MyAction(string MyControl) {
// MyControl contains the value of the input with name MyControl
}
The MVC pattern was designed to keep things separated.
The View has no knowledge of the controller at all
The Controller only knows that a view exists and what kind of data that it needs. It do not know how the data is render.
Hence, you can never get information about controls/tags in the view from the controller. You need to use javascript/jQuery in the view and invoke the proper action in the controller.
In an MVC-application you don't have controls like in a webform-application.
In MVC you collect your required data in the controller and pass it to the view.
Typicaly the view is a HTML-page with embedded code.
In opposite to controls in webforms which produce HTML and handles the post-backs in MVC you have to do all this manually. So you don't have controls with properties and events wich you can access easily in the controller and you have to handle all your posts with your own code.
Thats sounds as it is a lot of more work - and indeed it could be if you implement the behaviour of complex controls - but MVC applications are much better to maintain and you have 100% influence to the produced HTML.
Well probably i am late for this but it should help others in future...u can store ur value in hidden field in view and then access that value in controller by following code..
Request.Form["hfAnswerOrder"].ToString();
Point - hfAnswerOrder is the ID of the hidden field
My Control in cshtml page..
#Html.Hidden("hfAnswerOrder", Model.Answers.ToList()[0].AnswerOrder)

Display Messages in ASP.NET MVC 3

I am using MVC 3 Razor for my website. My requirement is that I want to show display friendly messages to the user on Success/Failure of the request, on the View itself, don't want to re direct the user to another View. I want like I could customize the display like Green color with some Success image and Red color for failure and respective image.
What would be the best approach?
It sounds like you want to know if a request failed or succeeded based on user input. If you are posting data to the server, you want to consider using the AjaxHelper the BeginForm-method takes an argument of AjaxOptions.
On the AjaxOptions you can specify OnSuccess and OnError among others and when one of these are called, you can call the corresponding JavaScript.
If this on the other hand is not enough, you might want to inspect the data that came from the server and based on that decide if the request succeeded or not, you want to use jQuery and their ajax-components. Here's an example of how to use the jQuery-option:
$.post("/MyController/MyAction", function(data) {
// Check what data contains.
});

Resources