Get query string from an ajax call - c#

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.

Related

Ajax begin form not picking up strong type drop down list value

I am using Ajax begin form for a search page to bring back results. I have the following markup.
#using (Ajax.BeginForm("GetSearchResults",
"MYController",
new
{
siteID = Model.SiteID
},
new AjaxOptions()
{
HttpMethod = "GET",
AllowCache = true,
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "search-reults"
}))
{
#Html_DropDownListFor(model => model.SiteID, Model.StatusCollection)
}
There are a few other strong type textboxes and a submit button on the page. All textboxes submit data back to the controller but the drop down list doesn't. It always submits the default value 0. Are there any other steps I need to do to pick up the value or something in the JQuery onchange event?
Removing the route parameter siteID worked. I do not need to pass strong type control values through as route parameters.

How do I pass EditorFor Value to Controller Method

Please assist, I have the following Ajax code
#Ajax.ActionLink(linkText: "Call An Action",
actionName: "GetCoverDate",
routeValues: new { appd = Model.AppDate },
ajaxOptions: new AjaxOptions
{
UpdateTargetId = "ajaxtarget",
InsertionMode = InsertionMode.Replace
})
My Controller Action
public string GetCoverDate(DateTime appd)
{
return appd.AddMonths(6).ToString();
}
What this does is it takes the contents of Model.AppDate and adds 6 months to it via ajax and controller's method and displays the results in a div
I'm trying to have the following changes to the code.
Insert the returned results (date) to the appropriate EditorFor (at
the moment I'm displaying the result in a div - ajaxtarget)
The routeValue as it is, passes a date that was set as default when
the view was loaded, how do I pass the value currently contained on
the EditorFor (in case the user has selected a different date)?
Thank you in advance

Prevent updating html with some conditions in MVC Ajax.BeginForm?

I have the following code in my View,
It's for searching in a site, a user can submit the following form multiple times.
#using (Ajax.BeginRouteForm("Search", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchContents",
LoadingElementId = "SearchAjaxLoader",
OnSuccess = "SearchLoadContentsOnSuccess",
OnFailure = "SearchLoadContentsOnFailure",
OnBegin = "SearchLoadContentsOnBegin",
OnComplete = "SearchLoadContentsOnComplete",
}))
{
#Html.AntiForgeryToken()
<input type="text" name="Search" />
<input type="submit" value="Submit" />
}
I wanna reject old ajax results and show the latest ajax result only.
In a non mvc Ajax form, I was creating an array as ajax counter and compare the server responses with it to prevent update html.
I wanna know how I can prevent Ajax.BeginForm to update Html on some conditions.
As an example I will demonstrate with an OnSuccess call, you can do this for each event you wish to handle.
In your AjaxOptions remove this to prevent the replace;
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchContents",
In you SearchLoadContentsOnSuccess JavaScript method, without seeing the method I am guesing it will be something like this:
function SearchLoadContentsOnSuccess()
{
// Do something
}
Change it to this:
function SearchLoadContentsOnSuccess(e)
{
// Do something
}
Now the e parameter will contain the data that is sent back from your ajax call.
In your updated method, I would simply check the response and act acordingly.
As an example if you response contains a value and results property:
function SearchLoadContentsOnSuccess(e)
{
// Do something
$(e.value == 1)
{
$('#SearchContents').html(e.results);
}
}
You would simply change the javascript in the above method to suite your needs.

ActionLink with HttpMethod=DELETE does not work

I try to implement DELETE method for my mvc-application.
There is my link placed in View:
#Ajax.ActionLink("Delete", "Delete", "Users", new { userId = user.Id }, new AjaxOptions { HttpMethod = "DELETE" })
There is my controller method:
[HttpDelete]
public ActionResult Delete(string userId)
{
//...
return View("Index");
}
When I click on Delete-link, I get a 404 error.
In Fiddler I see, that my request perfomed by GET method!
If I execute DELETE request with the same Headers from Fiddler, I get the expected result - my request is coming right into the Delete method.
How can I use #Ajax.ActionLink correctly?
P.S.: I want to use only built-in methods.
Are you sure all the Unobtrusive libraries are loaded? An #Ajax.ActionLink generates a standard anchor tag. If the JavaScript libraries aren't loaded to handle the click event, you'll get the GET request you see in Fiddler.
Check to see if the jquery.unobtrusive-ajax.js script is included in a bundle that is referenced from your layout page or that you're explicitly loading it on specific pages in a scripts region.
Try this:
#Ajax.ActionLink("Delete", "Delete", "Users",
new { userId = user.Id },
new AjaxOptions { HttpMethod = "POST" })
I am not sure why you used 'Delete' for the HTTPMethod. Post will send the Id for data you want removed to the server and call the 'Delete' ActionResult specified here #Ajax.ActionLink("Delete", "Delete", "Users",.

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

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", ...

Categories

Resources