I know that this question may not be fit for stack overflow. I've been searching for an example on how to use the ajax helper but most toturials have only gone through the helper and they have not provided any practical example. I already know how to make use of ajax the javascript way but just want to know how I can use the ajax helper that microsoft has provided.
To describe how this GitHUb branch works:
First, let's define an action we're going to request. To keep things simple, let's just make a very basic POST action:
//
// POST: /Home/Ajax
[HttpPost]
public PartialViewResult Ajax()
{
// use partial view so we're not bringing the entire page's theme
// back in the response. We're simply returning the content within
// ~/Views/Home/Ajax.cshtml
return PartialView();
}
Next, setup a destination for your content and give it an id (here I've named it "update-me"):
<div class="well" id="update-me">
Click the button to see some AJAX content.
</div>
Moving on from there we setup the form. The below demonstrates the standard AJAX functionality, but you could bind your own functions to some of the events specified by AjaxOptions.
#using (Ajax.BeginForm("Ajax", new AjaxOptions {
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "update-me" // place content within #update-me
}))
{
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-refresh"></i>
Click Me!
</button>
}
And finally, we need to specify our script libraries responsible for most of the ["automatic"] wiring up of the form functionality:
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
That's it. As you begin playing with it you'll find it's pretty simple to extend it. For example, if you wanted to show a "working" icon you could specify custom functions in the OnBegin and OnComplete properties.
Ajax helper of ASP.NET MVC essentially provides Ajax functionality to your web applications. AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. Using Ajax helper you can submit your HTML form using Ajax so that instead of refreshing the entire web page only a part of it can be refreshed. Additionally, you can also render action links that allow you to invoke action methods using Ajax. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc.Ajax namespace.
AJAX-enabled link based on action/controller example:-
Following example shows how to use AJAX action link using action and controller in Asp.Net MVC.
#Ajax.ActionLink("Fatch Data", "GetData", new AjaxOptions {UpdateTargetId = "Data-container", HttpMethod = "GET" })
Here is the html output of above code block.
Output:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Data-container" href="/Home/GetData"> Fatch Data </a>
Do you know Unobtrusive AJAX in MVC?
The Unobtrusive Validation and AJAX support in ASP.NET MVC follow many best practices that enable Progressive Enhancement and are also super easy to use. The unobtrusive AJAX library (not the unobtrusive validation library) is admittedly a bit limited in functionality, but if it satisfies the requirements of the application you are writing, then by all means use it. And because the source code of it is in your app (it's JavaScript, after all), it's generally straightforward to make any updates or changes to it as you see fit.
Related
I have a suite of several MVC3 web applications, all of which reference a common Core.dll. I have compiled common views using RazorGenerator, and the subscribing sites find the relevant views from the pre-compiled .dll without any problem.
I am trying to do the same for the layout page, as this is common across all the sites too, save for one or two divs that are specific to that particular site. This also works fine, in as much as the _layout view is served up by just doing this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
But, to get the site specific divs in the layout populated, I want to have a partial view in the specific site and use JQuery to set the HTML of the placeholding div in the _layout. Something like:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
//Have a hidden div containing the partial view that sits in the specific site
<div id="SiteSpecificStuff" style="display:none">
#Html.Partial("_SiteSpecificStuff", model)
</div>
// Use jQuery to populate the html of the placeholding div on the _Layout
// with that of the partial view
<script type="text/javascript">
$(document).ready(function () {
$("#divPlaceHolderOnLayout")
.html($("SiteSpecificStuff").html());
});
</script>
I have tried this but the _ViewStart does not re-fire on every post. Is this possible using a different approach?
I think you're looking for this:
#RenderSection("YouSection", required: false)
Ember.js has a great mechanism of binding data to views, of setting triggered event handling in the view, or using a Router. But what I would need is to be able to handle events triggered in already created HTML code (by PHP, server-side).
Let me show you a simple example. I have this code:
<a id="login" href="#">Login</a>
I need to be able to route/handle the click on this link so that it gets into my Ember application.
I have been looking for ways to do this, but I can't find any.
How can I do this?
If this link is inside a DOM element which is a child of the Ember managed element, then you can use the action helper:
<a id="login" href="#" {{action doSomeStuff}}>Login</a>
This doSomeStuff event will be sent to your Ember.Router, which has to implement the handler in the appropriated route:
...: Ember.Route.extend({
doSomeStuff: function (router) {
//...
}
}),
If the link is outside your app's scope, you can register handlers on the app-related elements using JQuery:
$('a#login').click(function () {
App.router.transitionTo('the.route.path');
});
The App.router being injected at Ember app's initialization, you can access it from anywhere.
But let me say that it is not a best practice to transition from outside the router.
Last but not least, you can also pass a context to the transitionTo call.
I'm new to Grails and got some problem with the g:formRemote command..
I want a g:textArea box send a message to my controller and save this messages.
After that the page should be updated via the formRemote Ajax, so that the messages appear on the page.
But instead of updating the page, the formRemote call assumes the given url to be a real link and wants me to redirect to this (non-existing) .jsp site.
The Method I want to start is called in my controller tho
I tried many solutions offered in similar problems, but it seems this problem is different from theirs
Heres the code:
<div id="history">
<g:render template="posts" collection="${ messages }" var="message" />
</div>
<div class="postMessageForm">
<g:formRemote name="postChatMessage" url="[controller: 'meetingRoom',
action: 'postMessage']" update="history">
<div class="msg_box">
<g:textArea name="message" value="" style="width: 630px"/><br/>
</div>
<div style="float: right;">
<g:submitButton name="Send" style="width: 90px; height: 40px;"/>
</div>
</g:formRemote>
</div>
and this is the Action which is called in my MeetingRoomController:
def postMessage() {
if (params.message != "") {
def thisUser = lookUpUser()
def thisRoom = thisUser.joinedRoom
def chatPost = new ChatPost(
message: params.message,
author: thisUser
)
thisRoom.addToChatHistory(chatPost)
}
// def messages = currentChatHistory()
// render template: 'posts', collection: messages, var: 'message'
I saw this kind of approach in Jeff Browns Twitter tutorial.
Possible failures i am seeing:
the out-commented render template command has something to do with the Ajax (When I do not comment it the only thing that happens is that the template posts will be rendered on the redirected page
usage of both Ajax and jQuery (But i dont believe that can be the point because I just have used g: and groovy stuff and havent even imported a jQuery lib)
this could be easier with remoteFunction (I dont really know how to get the remoteFunction work in this case tho)
I hope this information is enough to let someone see what I am missing
When the submit button is clicked on your form, the data is sent to the method listed in the url parameter of the formRemote tag. Then you are inside that method, you get to the commented out render tag that outputs data back to the gsp page in the div mentioned in the update tag of the formRemote tag.
formRemote relies upon a javascript library to handle the ajax stuff as mentioned in the grails documentation:
7.7.1 Ajax Support
By default Grails ships with the jQuery library, but through the
Plugin system provides support for other frameworks such as Prototype,
Dojo:http://dojotoolkit.org/, Yahoo UI:http://developer.yahoo.com/yui/
and the Google Web Toolkit. This section covers Grails' support for
Ajax in general. To get started, add this line to the tag of
your page:
You can replace jQuery with any
other library supplied by a plugin you have installed. This works
because of Grails' support for adaptive tag libraries. Thanks to
Grails' plugin system there is support for a number of different Ajax
libraries including (but not limited to):
jQuery Prototype Dojo YUI MooTools
So remove what is in the history div, uncomment the two lines in your postMessage method, and include one of the referenced javascript libraries.
I have a page with a lot of buttons on it. I need to get data from database when I click on each of them . I need to implement some jQuery styling for which I need to use AJAX to do it. How do I pass the url of the button to the "ajax.php" page(where my processing is done and where I can use my GET method to retrieve data from the database).
A few points of clarification:
First, jQuery can be used for communication via AJAX, and also for "styling" (that is, controlling layout elements and interacting with CSS. However, styling and AJAX do no intersect. AJAX is used to allow a page to communicate with a server. Styling controls how the page looks and acts.
Second, buttons do not have URLs. You can give them IDs, classes, or names, but not URLs. As noted in the comments, you can wrap your button in an anchor tag (<a>) to easily assign an action to it.
If you are already comfortable with building HTML forms and passing data to server-side scripts for processing, I suggest that you check the jQuery website for helpful documentation and tutorials.
If you are unfamiliar with HTML forms, there are a great many tutorials available via your favorite search engine.
If you are unfamiliar with server-side scripting, PHP is a language that is easy to pick up and learn quickly.
Well as your buttons are actually links you can do something like following
HTML:
<a class="btn" href="myurl.php?id=2"></a>
Jquery:
$('.btn').click(function(event){
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'GET',
success: function(data){
alert('server respond with' + data)
}
});
})
<a class="button" href="page.html">do some ajax</a>
<script>
$('.button').click(function() {
var btn_url = $(this).attr('href');
$.get('ajax.php', {url: btn_url}, function(data){
alert('done');
});
return false;
});
</script>
Since you talk about "buttons" and "urls" I think you mean <a>-tags styled as buttons, because <button> does not have something like a href-attribute. <a>-elements should not be abused as buttons - that's what <button> is for, actually. You can apply some information to the id or class-attribute though, e.g.
<button class="button" id="page">do some ajax</button>
Then you could gather the 'url' with
var btn_url = $(this).attr('id')+'.html';
So have a look at jQuery.get (or jQuery.post, if you like) and try to use XHTML in the way it was meant to ;)
Anybody? There is another question regarding this but the only answers were to code up some javascript validation, which also refuses to work on my partial view ("$ is not defined").
Anyway, I don't want to use javascript I just want simple validation for required fields that cannot be left blank, number fields that require ints, etc.
Can anyone shed some light on validation and partial views?
I suspect that you are loading those partial views using AJAX. If this is the case you will need to manually invoke the $.validator.unobtrusive.parse method once you inject the new contents of the partial into the DOM as explained in this article.
Brad Wilson also discussed this in his blog post:
The unobtrusive client validation script automatically parses the
initial set of HTML for validation rules when the page has finished
loading. If your page dynamically adds new HTML content (perhaps
throught Ajax or through client-side application code), you may wish
to parse that new HTML for client validation on the new HTML elements.
To parse new HTML, you can call the
jQuery.validator.unobtrusive.parse() method, passing it a selector for
the HTML that you would like to be parsed. You can also call the
jQuery.validator.unobtrusive.parseElement() function to parse a single
HTML element.
As far as the $ is not defined error you should make sure that you have included the proper scripts:
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Also make sure you are not referencing any of the Microsoft*.js scripts. They are obsolete and should no longer be used in ASP.NET MVC 3.
Of course that's only a supposition, you haven't shown any code so we cannot know what you are doing.
I'm having the same problem and i found that it's not possible to call $.validator.unobtrusive.parse() on the same form twice.
When loading the form initially from the server the form is parsed automatically by the unobtrusive library. When you add an input element dynamically to the form and call $.validator.unobtrusive.parse() again, it won't work. The same goes for parseElement().
So before you call $.validator.unobtrusive.parse, remove the original validator and unobtrusive validation from the form like so:
success: function (html) {
$("#div-id").append(html);
var form = $("#div-id").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($("#editorRows"));
}