ASP.Net MVC 3.0 Ajax Action Link OnBegin Function Collect return Value and Append to URL - asp.net-mvc-3

new AjaxOptions
{
OnBegin = "MyFunction",
Url="/Controller/JSONAction/"+OnbeginRetunrValue,
HttpMethod="GET"
}
In my Ajax properties, I have On Begin function which returns a value.
I wan tot append that return value to the URl.
How can I do that?

Well I realized i can't get this done the way I have asked.
But the Other way to Achieve it is have regular link and call jQuery Ajax Link
function CallActionResult(){
//do your logic
var newparam = //get your new param;
$.ajax({
url:"",
DataType:"JSON",
.....
continue rest of the properties.
});
}
this is how, I go this worked for me.

Related

Laravel render for differend controller method

I'm struggling with the render() method in Laravel 5.
When $whatever->render() is runned, it takes the controller method name as the route by default.
Example:
When i run this command in DelasController#updateFilter, the pagination route is set to whatever.com/marketplace/updateFiler?page=2, which does not make a sense to me.
Problem:
I want to keep the route as simple as whatever.com/marketplace?page=2.
Question:
Can anybody gives me a hint on how to solve this?
Thank you for your time and a discussion.
Looking forward for a reply.
I have an application in which various paginated lists are displayed in "windows" on the page and are updated via AJAX calls to the server. Here's how I did it:
Set up a route to render the whole page, something like this:
Route::get('/marketplace', function ($arguments) {
....
});
Set up a route which will return the current page of the list. For example, it might be something like this:
Route::get('/marketplace/updateFiler', function ($arguments) {
....
});
In your Javascript code for the page, you need to change the pagination links so that, instead of loading the new page with the URL for the link, it makes the AJAX request to the second route. The Javascript could look something like this:
$('ul.pagination a').on('click', function (event) {
// stop the default action
event.stopPropagation();
event.preventDefault();
// get the URL from the link
var url = $(event.currentTarget).attr('href');
// get the page number from the URL
var page = getURLParameterByName(url, 'page');
$.get('marketplace/updateFiler', { page: page }, function (data){
// do something with the response from the server
});
});
The getURLParameterByName function is simply a helper that extracts the named parameter from a URL:
var getURLParameterByName = function (url, name, defaultValue) {
// is defaultValue undefined? if so, set it to false
//
if (typeof defaultValue === "undefined") {
defaultValue = false;
}
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ?
defaultValue :
decodeURIComponent(results[1].replace(/\+/g, " "));
};
I adapted this code from an answer I found here on Stack Overflow: https://stackoverflow.com/a/901144/2008384.

Send Multiple data with ajax

I want to use ajax for add data in database and i found following code in net and it is working fine.
<script language='javascript'>
reqObj=null;
function saveCust(){
document.getElementById('res').innerHTML='processing';
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject('Microsoft.XMLHTTP');
}
reqObj.onreadystatechange=processSave;
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
reqObj.send(null);
}
function processSave(){
if(reqObj.readyState==4){
document.getElementById('res').innerHTML=reqObj.responseText;
}
}
</script>
Above code sends only one String but, i have 5 Strings in my form.
Please anybody alter the code for sending multiple data.
The problem is that you're sending a single parameter in the reqObj.open function:
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
Note that the only parameter you send is id.
You can add more parameters in the flavor of QueryString:
id=something&otherParameter=else //and more parameters
IMO the easiest way to handle an ajax request would be using jQuery, as shown and heavily explained by BalusC in How to use Servlets and Ajax?.
Based on the samples there and jQuery Ajax POST example with PHP, you can come with the following code:
Assuming the 5 Strings are in the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
Assuming there's data outside the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize() + "&id=" + $('#CustCode').val();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
And you can even enhance this using more jQuery functions, but that's outside the scope of this answer.

ASP.NET MVC 3, Ajax.BeginForm, OnBegin and form validation

I am using Ajax.BeginForm and wish to pass in parameters to the function called with OnBegin. The following are two code snippets.
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "DataEntrySummary",
OnBegin = "ValidateForm(11,55)"
}
function ValidateForm(minAge, maxAge) {return false;}
The parameters are passed in correctly to the ValidateForm function but the function always returns true.
If I take the parameters out and use
OnBegin = "ValidateForm()"
function ValidateForm() {return false;}
It works perfectly and returns false. Am I missing something or are parameters not allowed here or ...
Puzzled of Oxford - thanks in advance.
PS - I cannot use C# Attributes and Unobtrusive validation for very good reasons (these are code snippets).
Use
OnBegin = "return ValidateForm(11,55)"
function ValidateForm(a,b) {
return a<b;
}
I'm not sure how the comment from CrazyCoderz relates, but it is linked some how.
What I have found is that anything after the the function name causes the Ajax OBegin to return true. This includes OnBegin = "ValidateForm()". [My error above on the brackets]
I am now implementing a 'work around' - one of two - either write my own Ajax call or read the attributes from the test input element of the form to get the values I want. So, thanks CrazyCoderz for putting me on the track to a solution.

MVC3 redirect to action after ajax call

In an ASP.NET MVC3 Application I have a button in the view.
When the button is clicked a function is called and it jquery ajax call is made to save items to the database
function SaveMenuItems() {
var encodeditems = $.toJSON(ids);;
$.ajax({
type: 'POST',
url: '#Url.Action("SaveItems", "Store")',
data: 'items=' + encodeditems + '&storeKey=#Model.StoreID',
complete: function () {
}
}
});
}
What i want is after the items are saved to the database I want to redirect to another view. (Redirect to action)
How can I do that?
I tried to use return RedirectToAction("Stores","Store") in the controller at the end of the SaveItems function. But it is not working
I also tried to add window.location.replace("/Store/Stores"); in the complete function of the ajax call but didn't work either
Any help is greatly appreciated
Thanks a lot
You can use javascript to redirect to the new page. Set the value of window.location.href to the new url in your ajax call's success/complete event.
var saveUrl = '#Url.Action("SaveItems","Store")';
var newUrl= '#Url.Action("Stores","Store")';
$.ajax({
type: 'POST',
url: saveUrl,
// Some params omitted
success: function(res) {
window.location.href = newUrl;
},
error: function() {
alert('The worst error happened!');
}
});
Or in the done event
$.ajax({
url: someVariableWhichStoresTheValidUrl
}).done(function (r) {
window.location.href = '#Url.Action("Stores","Store")';
});
The above code is using the Url.Action helper method to build the correct relative url to the action method. If your javascript code is inside an external javascript file, you should build the url to the app root and pass that to your script/code inside external js files and use that to build the url to the action methods as explained in this post.
Passing parameters ?
If you want to pass some querystring parameters to the new url, you can use this overload of the Url.Action method which accepts routevalues as well to build the url with the querystring.
var newUrl = '#Url.Action("Stores","Store", new { productId=2, categoryId=5 })';
where 2 and 5 can be replaced with some other real values.
Since this is an html helper method, It will work in your razor view only,not in external js files. If your code is inside external js file, you need to manually build the url querystring parameters.
Generating the new url at server side
It is always a good idea to make use of the mvc helper methods to generate the correct urls to the action method. From your action method, you can return a json strucutre which has a property for the new url to be redirected.
You can use the UrlHelper class inside a controller to do this.
[HttpPost]
public ActionResult Step8(CreateUser model)
{
//to do : Save
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Stores", "Store");
return Json(new { status = "success", redirectUrl = url });
}
Now in your ajax call's success/done callback, simply check the return value and redirect as needed.
.done(function(result){
if(result.status==="success")
{
window.location.href=result.redirectUrl;
}
else
{
// show the error message to user
}
});
In action you can write this:
if(Request.IsAjaxRequest()) {
return JavaScript("document.location.replace('"+Url.Action("Action", new { ... })+"');"); // (url should be encoded...)
} else {
return RedirectToAction("Action", new { ... });
}
Try
window.location = "/Store/Stores";
Instead.

CI + AJAX, Double posting + refreshing of page

So I have a normal form with 1 textarea and two hidden inputs, which I would like to post via AJAX to a CI controller I have that inserts the information into the database.
The problem I'm having is that a) the page action is still called and the output of the controller is displayed and b) because the initial AJAX request is still processed plus the extra loading of the action target the information gets inserted twice.
This is my javascript code:
$(document).ready(function() {
$("#submit-comment").click(function(){
var post_id = <?=$p->id?>;
var user_id = <?=$user->id?>;
var content = $("textarea#content").val();
if(content == '') {
alert('Not filled in content');
return false;
}
$.ajax({
type: "POST",
url: "<?=site_url('controller/comment')?>",
data: "post_id="+post_id+"&user_id="+user_id+"&content="+content,
success: function(msg){
alert(msg);
}
});
});
});
I have tried doing
...click(function(e)... ... e.preventDefault
with no luck.
What am I doing wrong? :P
Thanks
Ps. All the information is processed properly and accessed, it's just the preventing the form which is screwing it up..
Just realised I was using a input type="submit", rather than input type="button".
Doh!

Resources