asp.net MVC Partial Views how to initialise javascript - javascript

I have an edit form that uses an ajax form to submit to the controller. Depending on the data submitted I redirect the user to one of two pages (by returning a partial view). Both pages rely on javascript/jquery and neither use anything common between the pages.
What is the best way to initialise these javascripts on each page? I know there is the AjaxOption OnComplete but both pages are quite dynamic depending on the Model passed and I would rather keep the javascript for both pages seperate rather than having a common method.
Thanks

If you are using jQuery then in the partial pages you can write
$(document).ready(function() {
// put all your javascript initialisation here.
});
Update: Above will not work. So you can try this.
You can call a method on On_PartialLoad() on AjaxOption.OnComplete. Each of this partial can provide there own implementation of On_PartialLoad().
So In Partial1 you can have
function On_PartialLoad(){
//Partial_1 Implementation
}
So In Partial2 you can have
function On_PartialLoad(){
//Partial_2 Implementation
}

Related

Struts 1, Get Function return in Java Script

I have a function called checkSubOffer in my Action class, which will return a Boolean value. I want this value in my JavaScript function docheckSubOf.
function docheckSubOf(){
thisForm.method.value = "checkSubOf";
}
is there a way to do it. I am using Struts 1
Generally speaking, you don't, at least not directly.
There are (at least) four options:
Option 1: Render your JavaScript in the JSP file, use normal S1 JSP methods to inject it into the JS. It will need to be properly JavaScript-escaped.
Option 2: Render your JavaScript through the JSP processor, e.g., add *.js to the list of files that need JSP processing. IMO not preferred, but it's an option. Other frameworks do this (like Rails ERb JS templates) but it's a little counter-inuitive, and can make finding functionality incrementally more difficult.
Option 3: Retrieve the value later via Ajax. Likely also not preferred since there's a mechanism you can use to avoid it. If there's a lot of other Ajax on the page it might not be as bad, but requires a new or modified JSON endpoint etc.
Option 4: Render the data into the JSP using normal JSP methods. The JS, which in general should be externalized to a .js file anyway, can refer to this data only after the page is fully reader, e.g., $(function () { ...data is ready... }.
You'd probably want to namespace/modularize the data as well, but that's a general good practice anyway.

Listen to Response on HTML Form embedded in GWT View?

I have a HTML like the following:
<div>
<form>
<input type="text" />
<button class="sendForm" value="Send form" />
</form>
</div>
<script>
// post the form with Jquery post
// register a callback that handles the response
</script>
I use this type of form a lot with a JavaScript/JQuery overlay that displays the form. That could be handled for example with plugins like FancyBox. I use Fancybox for Ajax content.
I also want to use this form embedded into a GWT view. Lets assume that the for cannot be created on client side because it has some server based markup language inside to set up some model data.
If I want to use this form in GWT I have to do the following. Tell GWT the form request url and use a RequestBuilder to query the html content of this form. Then I can insert it into a div generated by GWT. So far so good.
Problem:
When the user hits the send button the response is handled my the JQuery callback that is inside the script under the form.
Is there a way to access this callback from within GWT?
Is there a way to overwrite the JQuery send action? Since, the code is HTML and comes from the server I cannot place ui-binder UiFields inside to get access to these DOM elements.
I need to get the response if the submitted form accessible to GWT.
Is there a way how I can achieve this with JSNI?
Answers to each question:
1 Is there a way to access this callback from within GWT? actually you cannot modify the callback itself, what you can do from GWT is to call any jquery method, thus you can unbind any previous added handler, and set yours.
//NOTE: not wrapping code in $entry() to make a clearer code.
private static native unbindForm() /*-{
// remove all jQuery handlers added previously to my form
$wnd.$("my_form_selector").off();
// add a new handler for the submit event
$wnd.$("my_form_selector").on("submit", function(event) {
event.preventDefault();
$wnd.$(this).post(url, ...).done(function(data) {
// Use JSNI to call a GWT method
#.com.example.MyClass.handleFormResponse(*)(data);
// NOTE: that you can use a star instead of having to write parameter
// types, when you only have one method signature in your class.
});
}
}-*/
// handle the form response in GWT
public static void handleFormResponse(String data) {
// handle form response in GWT
}
Another thing you can do with GWT, is to wrap your form in a FormPanel and use specific widget methods to set a handler and read the response. But I think this is not what you are asking for.
2 Is there a way to overwrite the JQuery send action Yes, using JSNI to ask jQuery to unbind previously set events. See code in #1.
3 I need to get the response if the submitted form accessible to GWT. You have to include in the jquery.post callback some code to call GWT static methods (you can use-non static as well but this way is easier) this is also JSNI. See code in #1.
4 Is there a way how I can achieve this with JSNI? Of course, JSNI is the way to interact with handwritten javascript from GWT.
Aditional Notes:
GWT is designed to build RIA apps with very optimized js code. I know each one has their reasons for using external libraries, but adding 3party javascript to your app is against the main goals of gwt compiler remove death code and optimize output. If you like jquery like syntax and features for GWT I recomend to use gwtquery, which has been fully written in gwt, hence the compiler will include just the code you use.
Writing JSNI is a source of mistakes difficult to handle in the debugger. So I recommend to use gwt-exporter to populate java methods/classes or gwtquery to call external javascript. See these post I wrote some time ago: Pass value from GWT to Javascript via JSNI and Calling GWT Java function from JavaScript
Javascript => GWT and GWT => javascript values passing both can be done using JSNI . Please have a look here for more information about JSNI

MVC3 Using Javascript to postback similar to how $.post works -- but with an actual postback?

I have an ASP.NET MVC3 app that features a form with a nested-table input
(Ie on each row I can add a sub-table, with no limit on depth)
To handle this for my MVC app, I've created 2 javascript classes(using this term loosely with js:) that mirror my MVC3 model and post the data to an action method. Everything works great...Except that right now the only way that I know how to do this is with jquery $.ajax or $.post --- How can I do a postback in javascript?
I have the URL, and the custom JSON data, and want to do a page postback... Any suggestions? I can't use the normal form submit due to the nested table scenario described above.
Also, I just want to say, that MVC has made this so simple to render! :) For rendering a recursive view did everything without any script required, only on the saving did I need to screw around with json.
Update:I guess another solution would be -- can I change the contents of my form data on submit? My method takes a JSON object, is there any way I can stuff that in my request while my form submit is happening normally?
You can use the XML Http Request to do this. This is eventually what jQuery and other JS libraries use.
But why don't you just stick to jQuery AJAX or POST?
Maybe I'm misunderstanding your question, but it seems like what you want to do is post to the same page you are on, which means if you have the URL (and it sounds like you do), you just need to specific that in the $.ajax method? Maybe you can clarify what you mean a little bit for us.
Edit: Per comment suggested looking at http://jquery.malsup.com/form/
Well, I found that with the MVC3 binding, the table in my form could be normally bound if I named the fields such as Item[0].Children[1].Children[0].FieldA... etc, everything matched up fine without having to convert to javascript objects/json. I changed my code to fix this naming before a form submit, and it binds pretty well without having to do any json calls at all. Less elegant, but I guess it works.

Javascript Handling in MVC3

So, continuing in climbing my MVC learning curve, I would like to know how to effectivelly handle javascript in partial views. I mean coding a script in a partial view and then rendering the partial view twice in a view gives duplicate code, including variables and is generally conflictive.
How pros handle JS concurrency in ASP.NET MVC so each partial view see only its own JS code?
When you render a partial view within a view, you can still reference all of the HTML elements in that partial view from Javascript on the holding view.
This will not only help with duplication, but will add to the principle that code should be maintainable within one place in the codebase.
If I were you, I would put all Javascript that your partial views need in the main view, or better yet, in a Javascript file that is separate and reference it in a master page which your main view inherits from :)
This video gave me a great inside look into jquery with mvc it share also some best-practise...
mvcConf 2 - Eric Sowell: Evolving Practices in Using jQuery and Ajax in ASP.NET MVC Applications
http://channel9.msdn.com/Series/mvcConf/mvcConf-2-Eric-Sowell-Evolving-Practices-in-Using-jQuery-and-Ajax-in-ASPNET-MVC-Applications
def. worth a look...
Use external javascript file and reference it only in the full view. Put this line in the partial view so it does not load the stuff from the _Layout.cshtml
#{ this.Layout = null; }
you need to add the script at the bottom of the page before close the body tag place all required js their and place a rendersection('yoursection',false) so when you need you can define your section and just use the script their who would work in the page you need to define.
If you want javascript need to maintained effectively. Write that javascript in seperate js file. create another partial view and give the link to the js file. while rendering partial views, render the partial view which contains the link for that js file
I am not sure if it is the best way of doing this, but I certainly got it working for me.
So you write you javascript in an external file, and reference it in a partial view, then you could nest your partial view inside this partial view, so each of those nested partial view will be able to use the java script file on their parent level. So this way, you only reference the javascript once, but it can be used with all nested partial views.
good luck mate.
I think Dan Finch and user2745484 have answered the question. But as you sad scripts in partial views may override each other. For solving these problem you need to use some kind of object oriented programming to have encapsulation. Note that you may encounter these kind of problem everywhere you write JavaScript code.

Javascript validation and Zend_Form

I have extended Zend_Form to create my custom form that I will reuse on some pages of my site.
For this form I also created some JavaScript validation based upon jquery.
What I would like to do is add this JavaScript validation for the form in the sub-classed Zend_Form. So every time the form is called the JavaScript gets initiated as well.
In a view script you can use $this->headScript()->appendFile('/js/val.js') and than use echo $this->headScript() in the layout. But headScript() is to my knowledge not possible in Zend_Form.
How can I use headscript in Zend_Form or is their a alternative 'better' approach
You can use
$this->getView();
inside the form to get a reference to your view (via the view renderer). Use the view to access your view helpers then:
$this->getView()->headScript()->appendFile('/js/val.js');
I may add that I actually don't like this approach as it ties your form to the view, but it's the easiest and fastest way to do what you try to do.

Categories