I'm using Fancybox 1.3.4 with ASP.NET MVC 3.
I have following link :
<a id="various" href="Like/List/#feed.Id" class="petlikeCount liked">#feed.LikeCount</a>
and also jquery :
<script type="text/javascript">
$(document).ready(function () {
$("#various").fancybox({
type: 'ajax'
});
});
</script>
Controller action in Like controller :
public JsonResult List(int id)
{
return Json("success", JsonRequestBehavior.AllowGet);
}
My problem is that Like/List is never called (checked with the breakpoint) and fancybox just appears and show content of "parent" page....
I also tried with iframe content returning pure html back, but I'm getting same strange behavior as above.
Thank you in advance!
I'd recommend you using HTML helpers instead of hardcoding anchors:
#Html.ActionLink(
feed.LikeCount,
"List",
"Like",
new { id = feed.Id },
new { id = "various", #class = "petlikeCount liked" }
)
Another thing that you should make sure is that the feed.Id is actually an integer variable so that when the List action is invoked it is correctly passed this id.
So your url should look something like this: /List/Like/123. And then assuming tat you have kept the default route and haven't messed up with some custom routes, the List action should be called and passed the correct id as argument.
Also I would very strongly recommend you using a javascript debugging tool in your browser such as FireBug in which you will be able to see any potential errors with your scripts as well as the actual AJAX requests being sent which will allow you to more easily debug such problems.
Related
I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})
I have defined an action on my controller which accepts an integer and returns a string value:
public string SqlQuery(int listItemId)
{
return _sqlListSharePointList.GetSqlQueryFromCache(listItemId);
}
How could I call this action from my view? also what other options do I have apart from AJAX?
I tried the below but didn't work:
$.get('/SqlReportList/SqlQuery', 1, function (data) {
alert(data);
});
the "SqlReportList" is the name of my controller.
I also tried the below code:
$.get('/SqlReportList/SqlQuery/1', function (data) {
alert(data);
});
But it threw an exception on production that the listItemId is null.
Should I decorate my Action differently?
I also tried accessing it via fully qualified name but same error:
http://localhost:4574/SqlReportList/SqlQuery/1
Thanks,
If you do not want to use ajax (which is recommended) then only way to call the method is thru page refresh, only that way you are hitting your server side (controller) again from the view.
$.get('/SqlReportList/SqlQuery', { "listItemId": listItemId }, function (data) {
$('#tbSqlQuery').text(data); }
);
Is the parameter known at the time of rendering the surrounding page?
If so (and I've understood your question correctly) then you can use Html.RenderAction. See http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx
If not, then you can only really use AJAX or a full page reload. For getting the URL right for AJAX, you should be able to use Url.Action with some placeholder value.
The T4MVC project offers strongly-typed support for various things including action URLs, even supporting explicit placeholders for Javascript code. See section 2.2.2 of http://t4mvc.codeplex.com/documentation
My first post...
When I use RedirectToAction the url in the browser doesn't change. How can I achieve this?
I'm switching over to ASP.NET MVC 3.0 (also using jQuery Mobile) after 10+ years using web forms. I'm about 8 weeks into it, and after several books and scouring Google for an answer, I'm coming up dry.
I have a single route defined in Global.asax:
routes.MapRoute(
"Routes",
"{controller}/{action}/{id}",
new { controller = "Shopping", action = "Index", id = UrlParameter.Optional }
I have a ShoppingController with these actions:
public ActionResult Cart() {...}
public ActionResult Products(string externalId) {...}
[HttpPost]
public ActionResult Products(List<ProductModel> productModels)
{
// do stuff
return RedirectToAction("Cart");
}
The url when I do a get and post (with the post having the RedirectToAction) is always:
/Shopping/Products?ExternalId=GenAdmin
After the post and RedirectToAction I want the url in the browser to change to:
/Shopping/Cart
I've tried Redirect, and RedirectToRoute but get the same results.
Any help would be greatly appreciated.
[Update]
I found that jQuery Mobile AJAX posts are the culprit here. If I turn off jQuery Mobile's AJAX it works.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
// do not handle links via ajax by default
$(document).bind("mobileinit", function () { $.mobile.ajaxEnabled = false; });
</script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />
The ordering of the above scripts is important. I had to include the script to jQuery first, then include the script to disable jQuery Mobile's use of AJAX and then include the script to jQuery Mobile.
I'd still like to find a way to use AJAX and have the url update properly. Or at the least be able to call jQuery Mobile's "loading" message (or bake my own).
I think I've found an answer. Buried deep in the jQuery Mobile documentation, there is information about setting the data-url on the div with data-role="page". When I do this, I get the nice jQuery Mobile AJAX stuff (page loading message, page transitions) AND I get the url in the browser updated correctly.
Essentially, this is how I'm doing it...
[HttpPost]
public ActionResult Products(...)
{
// ... add products to cart
TempData["DataUrl"] = "data-url=\"/Cart\"";
return RedirectToAction("Index", "Cart");
}
Then on my layout page I have this....
<div data-role="page" data-theme="c" #TempData["DataUrl"]>
On my HttpPost actions I now set the TempData["DataUrl"] so for those pages it gets set and is populated on the layout page. "Get" actions don't set the TempData["DataUrl"] so it doesn't get populated on the layout page in those situtations.
The only thing that doesn't quite work with this, is when you right-click... view source... in the browser, the html isn't always for the page you are on, which isn't unusual for AJAX.
Not sure if it is still actual, but in my case I wrote following helper method
public static IHtmlString GetPageUrl<TModel>(this HtmlHelper<TModel> htmlHelper, ViewContext viewContext)
{
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.Append("data-url='");
urlBuilder.Append(viewContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped));
urlBuilder.Append("'");
return htmlHelper.Raw(urlBuilder.ToString());
}
And then use it as follows:
<div data-role="page" data-theme="d" #Html.GetPageUrl(ViewContext) >
This way I don't need for every redirect action store a TempData. Worked for me fine both for Redirect and RedirectToAction. This would not work properly in case if you use method "View()" inside controller and return different view name, which will change UI, but will retain url.
Hope it helps
Artem
David, this was a big help to me. I just wanted to add that in my case I had to use the following format to get the Url to display in the correct form as my other url's:
TempData["DataUrl"] = "data-url=/appName/controller/action";
return RedirectToAction("action", "controller");
As a side note, I also found that when assigning the value to TempData["DataUrl"] I was able to leave out the escaped quotes and enter it exactly as above and it seems to be working fine for me. Thanks again for your help.
There is an issue on github
https://github.com/jquery/jquery-mobile/issues/1571
It has a nice solution without the need of TempData
I am trying to implement an autocomplete in ASP.NET MVC 3, following this post
but I really can't get it to work. I have looked at a series of other posts and blogs, but no success so far.
I have a DB table which contains regions (in Japanese), like so:
1 ハイチ; 2 ドミニカ共和国; 3 南アフリカ
basically a [key, Name] pair.
In my repository I am doing the following call:
public IQueryable<Region> GetAllRegions()
{
return db.Regions;
}
Getting the raw data, which I pass to the controller, pair down the data according to input and the concatenate to a string like so:
public class RegionsController : Controller
{
Region_Repository rr = new Region_Repository();
public string FindRegions(string q)
{
List<string> regions = rr.GetAllRegions().Select(r => r.Name).Where(s => s.StartsWith(q)).ToList();
return string.Join("\n", regions);
}
}
The controller when accessed via server/Regions/FindRegions/?q=ハ return a page with the single entry "ハイチ" as expected.
On the page I have a textbox with id "#NewRegion" and the script
<script type="text/javascript">
$(document).ready(function () {
$("#NewRegion").autocomplete('#Url.Action("FindRegions", "Regions")');
})
</script>
which I placed underneath the textbox.
I have references to JQuery and JQueryUI from Google API which work since I am executing other JQuery and using the JQueryUI datepicker successfully on this page.
I tried placing the script in a separate file and hardcoding the url as '/Regions/FindRegions', but no change. I had a look in firebug (second day only, so not very proficient at using it yet) and the script doesn't seem to get executed.
The controller is called fine when accessed via URL, but anything I enter into the textbox does not get passed to the controller...
Can anybody see anything wrong with this?
According to the dark depths of the jQuery UI documentation, the parameter used when passing the autocomplete string to the server is called term, not q.
Update: And also, initialize with autocomplete({source: "#(...url...)"}).
Update 2: And also, return the type of data the Autocomplete widget expects, a JSON array of strings or a JSON array of objects.
I got it working in the following way. I changed the controller to return Json data like this:
public ActionResult FindRegions(string term)
{
var regionNames = rr.GetAllRegions().Select(r => r.Name).Where(s => s.Contains(term)).ToList();
return Json(regionNames, JsonRequestBehavior.AllowGet);
}
note: the AllowGet is there so I could check the result via url, so for debug only.
And the autocomplete script became:
$(function () {
$('#NewRegion').autocomplete({ source: '/Regions/FindRegions' } );
});
Now it works, but I am still not sure why.
I'm using jquerymobile and asp.net MVC3 razor. I'm somewhat new to this, but figuring things out, I have a very basic route table, with just the ignore route for .axd resources and a default route:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "", UrlParameter.Optional }
);
I have an action link that works in an .ascx page:
#Html.ActionLink("Log On", "LogOn", "Account", null, new { #class = "ui-btn-right" })
Now, when I get to the LogOn page, and I complete the account verification, I need to send them to the home page, /Home/Home which works if I type it in the address bar, but I can't seem to get my redirect working in the account controller: return RedirectToAction("Home", "Home");
Thanks for any help!
It sounds like maybe you're posting your form from /Account/LogOn via ajax. That means that when you return RedirectToAction("Home", "Home");, the page wouldn't change. So you just need to not use ajax on the form submit. If my guess is wrong, please post more code so we can get an idea of what the problem is.
It appears from the documentation that jQuery mobile handles form posts via ajax automatically. To prevent this, add the data-ajax="false" attribute to the form element. Documentation here: http://jquerymobile.com/test/docs/forms/forms-sample.html
Given what's written in documentation, could you put your code into a form element and setting its action property to /Account/LogOn ? In order to do that, you may have to convert your ActionLink into a button.
You can check for ajax request in controller:
if(Request.IsAjaxRequest())
{
//send json object and do navigate in client
return Json(new {IsLogged = true});
}
else
{
//send redirect html code to browser
return RedirectToAction("Home", "Home");
}
and in client side, check for json result if you post form by jQuery ajax.
I'm not use jquerymobile so I don't know how it work in client side.