Ajax.BeginForm says action doesn’t exists, however it does - c#

I am working with AJAX Helper method in one my applications, things were all good and right but suddenly am facing this strange problem i.e. in view
<% using (Ajax.BeginForm("Feedback", "User", new AjaxOptions { InsertionMode = InsertionMode.InsertBefore, HttpMethod = "POST", OnFailure = "searchFailed", OnSuccess = "feedbackRecorded", LoadingElementId = "ajax-loader-fb", UpdateTargetId = "newsletter", }, new { #id = "feedback" })) { %>
The first parameter to Ajax.BeginForm that is the {action name} is now being marked in red color(I am using Resharper) and says that ‘cannot resolve action ‘ActionName’’, however the Action is present in my controller.
Another strange thing is that on running the app and submitting the form it ends up invoking the Javscript’s "OnSuccess” method as if it has succeeded but in actually nothing happened and it didn’t even get to first line call of the specified controllers action. (This is happening to both AJAX forms in the view)
Does anyone have any ideas about the possible reasons forit to behave this way suddenly?
Thankyou!
I just created a new 'SharedController' controller with the same action in it and now it is recognizing but its is not recognizing in the UserController?
public class SharedController : Controller
{
public ActionResult Feedback()
{
throw new NotImplementedException();
}
}

Maven, about ReSharper - it's complaining right, because you use this method overload
public static MvcForm BeginForm(
this AjaxHelper ajaxHelper,
string actionName,
Object routeValues,
AjaxOptions ajaxOptions,
Object htmlAttributes)
where second parameter is routeValues, so ReSharper looks for action 'Feeeback' in current controller.
Obviously, you wanted another overload, with this invocation
<% using (Ajax.BeginForm("Feedback", "User", null, new AjaxOptions { InsertionMode = InsertionMode.InsertBefore, HttpMethod = "POST", OnFailure = "searchFailed", OnSuccess = "feedbackRecorded", LoadingElementId = "ajax-loader-fb", UpdateTargetId = "newsletter", }, new { #id = "feedback" })) { %>
Pay attention to third null argument.

The second parameter of Ajax.BeginForm is the controller name.
Try changing the code to:
<% using (Ajax.BeginForm("Feedback", "Shared", ...

Related

ASP.Net MVC Ajax.BeginForm OnComplete pass c# arguments in Razor view

I have the following code in a MVC c# Razor view:
#{string url = "/Projects/_MonthRangesScriptsPartial";}
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = "updategraphArrayScript(#url,#ViewBag.InputResourceID)"
}))
The code works almost perfectly, but I would like to resolve the c# variables to their values in the OnComplete line.
That is to say, the Razor engin should resolve the code to (for example):
<form action="/Projects/_MonthRanges/55"
data-ajax="true" data-ajax-complete="updategraphArrayScript(/Projects/assets,55)"
...>
Rather than:
<form action="/Projects/_MonthRanges/55"
data-ajax="true" data-ajax-complete="updategraphArrayScript(#url,#ViewBag.InputResourceID)"
...>
Simply create another variable string:
#{
string url = "/Projects/_MonthRangesScriptsPartial";
string onComplete = String.Format("updategraphArrayScript({0}, {1})", url, ViewBag.InputResourceID);
}
#using (Ajax.BeginForm(
"_MonthRanges",
"Projects",
new { id = ViewBag.InputResourceID },
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "MonthRanges",
InsertionMode = InsertionMode.Replace,
OnComplete = #onComplete
}))
Take off the # when you assign your OnComplete value. You don't need it since you're already in the context of server side code.
# is used to switch html rendering context to server side code, and <text></text> is used to switch from server side context to html rendering. In example given above, you're already in the server side code context of the BeginForm() method so the # is not needed. You're not writing the value of onComplete to the page, BeginForm() will handle all that.

Get query string from an ajax call

Hi I am trying to get a querystring from an ajax call and it does not seem to work so well.Here is my code:
#Ajax.ActionLink("Add To Cart" ,
"AddToCart" ,
"Products",
new {
ProductId = #products.ElementAt(0).Value
},
new AjaxOptions{
Url = "/Products/AddToCart",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "UpdateCart",
HttpMethod = "GET"
})
Each link I have in my application calls something like this:
Products/AddToCart?ProductId=5
This is the controller it calls:
public ActionResult AddToCart(string ProductId)
{
string ProductCeva = ProductId;
}
Now from what I learned so far about MVC3 I assumed that the parameter ProductId would be 5 in our case , but when I debug the code , I get that it is null.
What am I doing wrong here and how can I get the ProductId query string in this casE?
Remove the Url = "/Products/AddToCart", bit from your AjaxOptions.
Why?
Here's why. The following code:
#Ajax.ActionLink(
"Add To Cart" ,
"AddToCart" ,
"Products",
new {
ProductId = #products.ElementAt(0).Value
},
new AjaxOptions {
Url = "/Products/AddToCart",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "UpdateCart",
HttpMethod = "GET"
}
)
generates:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#UpdateCart" data-ajax-url="/Products/AddToCart" href="/Products/AddToCart?ProductId=5">Add To Cart</a>
Now even if the href of the generated anchor is correct (/Products/AddToCart?ProductId=5) that's not what is used for the AJAX request. The jquery.unobtrusive-ajax.js that you are using and which unobtrusively AJAXifies all anchors uses the data-ajax-url attribute (if present) when sending the AJAX request instead of the href attribute. Now look at the value of the data-ajax-url attribute and you will understand why you get null in your controller action.
You would also have seen this if you had used FireBug or a similar javascript debugging tool because when you would have inspected the Network tab to see why your AJAX request is not working you would have seen the wrong url being used.
Long story short two things to remember from this question (the first being more important as it allows you to deduce the second):
Use FireBug
the Url property of the AjaxOptions allows you to override the url to be used when sending the AJAX request.

Passing data to controller using Ajax.ActionLink

I am trying to write a link to a partial view on the same page. Everything works, except that I am not able to pass in the needed month parameter through my ajax.actionlink syntax. I've tried using the ViewDataDictionary, but to no avail. Also, RouteValueParameter was a thought I had, but I'm trying to pass a string, not an integer id.
Below is my code in the view, followed by the method in the controller:
<td>#Ajax.ActionLink("January", "ControllerMethod", new ViewDataDictionary{{"month", "January"}}, new AjaxOptions { UpdateTargetId = "view-month" })</td>
public ActionResult ViewMonths(string month)
{
//some code here
return PartialView("ViewMonths", schedule);
}
Any ideas?
Try this way
#Ajax.ActionLink("Link Text", "MyAction", "MyController", new { month = "January", plum = "2", moreparams = "U can do this all day"}, new AjaxOptions{ UpdateTargetId = "view-month" } )
Greatings

Get Mvc3 Ajax.ActionLink replaced data with Jquery?

I have an #Ajax.ActionLink that replaces his own wrapper, with another content that also has #Ajax.ActionLink, that returns first html content to wrapper. It's link to partial that replaces it's self and viceversa. My problem is that when i want some aditional functionaliti on click to ActionLink, my Jquery returns old partial, the one that has been click, and not the new, in firebug i clearly see my new elements, but cannot reach them, i tried, OnSuccess and OnComplete, but didnt succed! Any ideas?
Here's example:
VIEW
index.cshtml
<div id="box">
#Html.Partial("_PartialOne")
</div>
_PartialOne.cshtml
#Ajax.ActionLink("Get partial two", "getPartial2", "Home",
new AjaxOptions
{
UpdateTargetId = "box",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
},
new { #class="first"}
)
<div id="testBox1">Hello, I am partial 1</div>
_PartialTwo.cshtml
#Ajax.ActionLink("Get partial one", "getPartial1","Home",
new AjaxOptions
{
UpdateTargetId = "box",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
},
new { #class="second"}
)
<div id="testBox2">Hello there this is partial 2</div>
CONTROLLER
HomeController.cs
public PartialViewResult getPartial1()
{
return PartialView("_PartialOne");
}
public PartialViewResult getPartial2()
{
return PartialView("_PartialTwo");
}
JS
$("#box a.first").live('click', function () {
//how to fetch new data, that was filled with getPartial2()
console.log($(this).parent().children());
//this returns [a.first, div#testBox1]
// and I need [a.second, div#testBox2]
});
How to select returned data to let's say substring if neccesary??
EDIT
using OnComplete = "function"
VIEW
#Ajax.ActionLink("Get partial two", "getPartial2", "Home",
new AjaxOptions
{
UpdateTargetId = "box",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnComplete = "getNewData"
},
new { #class="first"}
)
<div id="testBox1">Hello, I am partial 1</div>
JS
function getNewData()
{
console.log($(this));
//this returns [Object] of ajax call, niether
// $(this).parent/s(), or $(this).children() is posible
}
How to select children of element that called this ajax?
I guess I am not 100% what you are looking for, but I think maybe your issue is caching. If you tack a unique parameter onto the GET request, do you get the result you are looking for?
#Ajax.ActionLink("Get partial two", "getPartial2", "Home", new { aparam = DateTime.Now.Ticks },
new AjaxOptions
{
UpdateTargetId = "box",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnComplete = "completeGetThing"
},
new { #class="first"}
)
<div id="testBox1">Hello, I am partial 1</div>

How to create a default AjaxOptions for Razor Views?

How do I create a default AjaxOptions? For example, I have a menu with some links, I want to make the entire website to use the same loading element and same error handling.
#Ajax.ActionLink("Home", "Index", "home", <AjaxOptions>)
new AjaxOptions()
{
OnFailure = "handleError",
LoadingElementId = "loading"
});
But then I have some links that update the content and I want to set UpdateTargetId for each of those links. How can I keep a default error handling and loading element on all the views and edit only UpdateTargetId or OnSuccess (or another property) for each link?
Something like
#Ajax.ActionLink("home", "Index", "home", ajaxOption.UpdateTargetId = "content")
#Ajax.ActionLink("menu", "Foo", "home", ajaxOption.UpdateTargetId = "side-content")
I want something equivalent to jQuery.setup where I can set the default values to ajax requests and when I make an ajax request I only tell the parameters I want to override...
You could do something like:
public static class AjaxExtensions
{
public static IHtmlString DefaultLink(this AjaxHelper helper, string text,
string action, string controller, string updateTargetId = "",
string onSuccess = "")
{
// Build your link here eventually using
// the arguments passed
var options = new AjaxOptions
{
OnSuccess = onSuccess,
UpdateTargetId = updateTargetId,
OnFailure = "handleError",
LoadingElementId = "loading"
// etc...
}
// return a normal ActionLink passing your options
return helper.ActionLink(text, action, controller, options);
}
}
Note I'm using optional parameters in the signature to benefit from the flexibility of multiple overloads without the nuisance of maintaining them. Expand as needed :)
Then just use it as follows:
#Ajax.DefaultLink("home", "Index", "home", updateTargetId: "content")
I found it easier to inherit the AjaxOptions class and instantiate DefaultAjaxOptions in my view. This means you can use it for things like Ajax.ImageActionLink if you have one of those without creating a separate extension method. See example below, the only thing I needed to change was the target so I allowed this to be passed into the constructor.
public class DefaultAjaxOptions : AjaxOptions
{
public DefaultAjaxOptions(string target)
{
InsertionMode = InsertionMode.Replace;
UpdateTargetId = target;
OnBegin = "BeginLoadingSection()";
OnFailure = "FailureLoadingSection()";
OnSuccess = "SuccessLoadingSection()";
}
}
then in the view use:
#{ var ajaxOptions = new DefaultAjaxOptions("name-of-content-div"); }

Categories

Resources