asp.net mvc: simulating autopostback for simple checkbox - asp.net-mvc

I have a simple checkbox, generated with:
<%= Html.CheckBox("myCB" )%>
How can I add an onChange handler to this that does a submit?

Add an onClick handler to the CheckBox that submits the form the CheckBox belongs to...quick, clickHandler codeless example:
<%= Html.CheckBox("myCB",
new { onClick = "$(this).parent('form:first').submit();" });
(example definitely not checked for accuracy)

If you have only one form, and are not using JQuery (you should be, by the way) try this:
<%= Html.CheckBox("myCB",
new { onClick = "document.form.submit();" });

I would highly recommend using jQuery to support this because it makes it easier to add the behavior to a checkbox throughout your site by having the selector either be ID or class-based. Then you could put the script anywhere on the page or in an external .js file.
<script language="javascript" type="text/javascript">
$('#myCB').click(function() { $(this).parent('form:first').submit(); });
</script>
Alternatively, the selector could be class-based (or any attribute for that matter). More info here: http://docs.jquery.com/Selectors

Related

How to use pageinit correctly?

I have a single file for each page and i am trying to implement the pageinit event handler on every page (I think what belongs strictly to one page, should be declared there) as shown below:
<body>
<div id="myPage" data-role="page">
<!-- Content here -->
<script type="text/javascript">
$("#myPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
The event is bound properly to the page, so the code is executed but - now my problem - if i go to another page and return later on the pageinit event will be executed twice. I think that is because the .live method binds the pageinit event again to the page. But shouldn't the pageinit event only called once at page initialization? What I am missing here?
I solve the issue by passing the name of the event, in this case the "pageinit" instead of the handler.
<script defer="defer" type="text/javascript">
var supplier = null;
$("#pageID").die("pageinit"); //<--- this is the fix
$("#pageID").live("pageinit", function(event){
console.log("initialized - #(ViewBag.ID)");
supplier = new Tradie.Supplier();
supplier.Initialize("#(ViewBag.ID)");
});
Ref: http://www.rodcerrada.com/post/2012/04/26/jQuery-Mobile-Pageinit-Fires-More-Than-Once.aspx
I think its probably best to move your JavaScript code into another file as while your navigating around your site jQuery Mobile may cleanup (read: delete from DOM) that myPage page and therefore will have to load it in again and hense rerun that same block of code you defined and bind 2 listeners for the pageinit event.
Thats basically why they suggest using the live or on functions however it falls over if you include the binding code on the page ;)
However if you insist on having your code placed on a per page basis than use bind instead of live.
Ref: http://jquerymobile.com/demos/1.0/docs/pages/page-cache.html
jQuery Mobile therefore has a simple mechanism to keep the DOM tidy. Whenever it loads a page via Ajax, jQuery Mobile flags the page to be removed from the DOM when you navigate away from it later (technically, on the pagehide event).
I'm pretty sure they recommend binding pageinit to the document using on(). E.g.
$(document).on ('pageinit', '#myPage', function (event) {
instead of having the pageinit bound to the page, which is getting re-inited. In fact, I thought $(document).on() was the recommended way to bind events in jQuery, in general, now.
A quick workaround I have used is declaring a variable containing the handler function.
var handler = function() {
// your code
};
Then always use die() before binding the handler with live()
$( "#myPage" ).die( handler ).live( handler );
I'm sure this is not the intended usage by the authors, but it does the trick, you can leave your code within the page DIV.
$("#page1").live("pageinit", function () {
alert('pageinit');
$("#page1").die("pageinit"); //<--- prevent from firing twice on refresh
});

set ActionLink routeValues dynamically

I'm working on reading a value from textBox (let it be Sam):
<%= Html.TextBox("Name")%>
and then on click of action link:
<%: Html.ActionLink("Edit","Edit",routeValues %>
I need to route (this URL should open) /Edit/Sam
How can I do that?
Since you aren't using any route values above and instead just the name of the textbox you can just create a link
Name your textbox "name" (if it isn't already) via the html attributes new {id="name"} (for ex)
then you can just jQuery to get the value and append it
Edit
You could also use the html help above and just attach an onclick event handler for jQuery as well.
$(document).ready(function() {
$("#name").click(function() {
window.location.href= $('#idOfLinkHref').attr('href') + '/' + $('#name').val()
});
});
something like that anyways off the top of my head.
There are a lot of ways to do this - these are just a couple ideas.

Rails - Using jQuery to populate a form

on my page I have the following:
<span id="attach-file" class="link">Attach a file</span>
<div id="attach-file-form">
</div>
Give that attaching a file is not a common use case, I don't want the attach-file-form elements to be present on load, it would slow everything down.
What I would like to happen is the user clicks "Attach a file", jQuery AJAX GET to get the form and inject it inside of attach-file-form.
What's the right way in Rails to go about this?
in jQuery I have:
$("#attach-file").live("click", function() {
DO A GET TO A custom Method in the Attachment Controller
Inject inside the div
});
Does this sound right?
Having the file upload form present on the page but hidden will have pretty much zero impact on the performance of your site. I'd recommend just defaulting the file upload form to hidden, and triggering display of the form when your button is clicked.
Then your JQuery code can be as simple as:
$("#attach-file").live("click", function() {
$("#file_upload_form").show();
});
If you do need to get this from the server, you can use the jQuery.get method to make a call to a Rails controller, which can output the form for you:
$("#attach-file").live("click", function() {
$.get("/controller/action", function(html) {
$("#file_upload_form").html(html);
}
});

Get tinyMce mode to activate on a new textbox inserted by AJAX (in Rails)

I have a nested attribute (speeches) under a model Speaker and I'm using tinyMce to let a speaker fill out a profile form where they might have one or more speeches they give.
I'm using the Rails 2.3 nested attributes helpers as used in Ryan Bates's complex-form-example github account.
The tinyMce functionality is great for a "Speech" if it's loaded by the page, but not active for a new "Speech" loaded by AJAX on "Add new speech" (calls a insert_fields script to add the form fields)
The tinyMce code on the page is
<script src="/javascripts/tiny_mce/tiny_mce_src.js?1254270151" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
tinyMCE.init({
editor_selector : 'mceEditor',
language : 'en',
mode : 'textareas',
theme : 'simple'
});
//]]>
</script>
And to activate a textarea form field, you put class="mceEditor" on it.
Is there a way to activate tinyMce on the new Ajax inserted form fields?
TinyMce plugin: http://github.com/kete/tiny_mce
You can create a new editor after TinyMCE has been initialized using:
var new_editor = new tinymce.Editor('new_id', {
});
new_editor.render();
This won't utilize the settings you have in your controller, and is a pure javascript solution, not really a ruby one, but you should be able to easily run it after your ajax call completes and you have the id of the new text area.
I don't know if this is a good answer; but for this situation (someone following the Railscast on nested attributes and complex forms and wanting to use tinyMCE)
pasting
<script type="text/javascript">
//<![CDATA[
tinyMCE.init({
editor_selector : 'mceEditor',
language : 'en',
mode : 'textareas',
theme : 'simple'
});
//]]>
</script>
Into my insert fields function made it worl

Display different forms on Index page depending upon link clicked in ASP.NET MVC

I have a menu control on Index page rendered as <% Html.RenderPartial("MenuUserControl"); %> where MenuUserControl is something like
<li><%= Html.ActionLink("Link1","Index") %></li>
<li><%= Html.ActionLink("Link2", "Index")%></li>
<li><%= Html.ActionLink("Link3", "Index")%></li>
Now I wan to load three different form in Index page itself onclick of these links, with first form being loaded on Page load. How can I do this. Any help is appreciated.
If you need to pass information about links to RenderPartial
<% Html.RenderPartial("MenuUserControl", new[]{"link", "link"}); %>
however it's better to pass a custom model (class object) rather than array of strings.
Use Ajax.ActionLink to load form without page reload.
To load first form either do this in the Index page itself (add HTML tags or call RenderPartial to render form, or use RenderAction), or add script to the menu partial like this
<script type="text/javascript">
$(function(){ $("a").eq(0).click(); }
</script>
This requires jQuery, though.
If you don't know what I'm talking about then you better prepare to learn a lot.
You will need some sort of JavaScript library like jQuery to do this, the rest is imagination:
-You can pre-load the 3 forms on pageload and then hide the last two on DOM ready (PageLoad). i ll wrap this in div just for convenience.
<script type="text/javascript">
$(document).ready(function () { //This is like DOM ready
//here we hide the the last 2 forms
$('#div_id_form2').hide();
$('#div_id_form3').hide();
//Next set the events for the links (on click show form)
//on link 2 click
$('#link2').click(function(){
//show the second form
$('#div_id_form2').show();
});
//on link 3 click
$('#link3').click(function(){
//show the third form
$('#div_id_form3').show();
});
});
</script>
The other option is go the Ajax way but requires more code and knowledge in jQuery.
If you are interested refer to http://docs.jquery.com/ thats the API reference for jQuery.
If you are moving to MVC, I recomend you to learn any JavaScript library to help you with this kind of behaviors that some call DHMTL (Dynamic HTML).
First do the Non Ajax Version.
Have 1 page Index with 3 partials in it. Each partial has only the html for the form to display in it.
In your actions set the ViewModel (here Action Link1)
model.IsForm1Visible = true;
In your View use the model to display partials
<div id="linkContainer">
<% if(Model.IsForm1Visible){%>
<%= Html.RenderPartial("Form1")%>
<%}%>
<% if(Model.IsForm2Visible){%>
<%= Html.RenderPartial("Form2")%>
<%}%>
<% if(Model.IsForm3Visible){%>
<%= Html.RenderPartial("Form3")%>
<%}%>
</div>
If you need Ajax you can continue from there.

Resources