I am trying to call my Child action on clicking any link. Basically what I know is Child Actions are called with #Html.Action() method. But this methods gets invoke automatically inside our view. I am trying to use #Html.ActionLink() but this is not working. Is there any way that we can call our Child actions on clicking any link.
You could use an AJAX link which will invoke the action and inject the partial result into the DOM. For example assuming you have the following action:
public ActionResult Foo()
{
return PartialResult();
}
you could write an action link and a div to hold the results:
#Html.ActionLink("click me", "someaction", "somecontroller", null, new { id = "mylink" })
<div id="result"></div>
and then in a separate javascript file AJAXify this link:
$(function() {
$('#mylink').click(function() {
$('#result').load(this.href);
return false;
});
});
Related
I have a View with a Form that calls a controller action Post Method to "Complete" a Package. It then needs to refresh the page its on as that contains information that will be updated, both within the view itself and also within a partial. It does use two different Controllers in different MVC Areas.
The Post works correctly and the redirect is issued, but the page is not refreshed.
I have read that instead, I should use OnSuccess within the Ajax call that calls Complete, but I thought that was for in page calls, not ones that navigate to different pages.
View Form
#using (Ajax.BeginForm("Complete", "Packages", new { Area = "Core" },
new AjaxOptions
{
HttpMethod = "POST"
}))
{
Core(Area) Packages Controller
[HttpPost]
public ActionResult Complete(int ID)
{
// Update code
// Refresh the full page
return RedirectToAction("Summary", new { Area = "Control", id = packageBuilder.CurrentPackage.ID });
}
Control (Area) Packages Controller
[HttpGet]
public ActionResult Summary(int id)
{
// Get Model
return View("Summary", model);
}
Any pointers would be warmly welcomed.
Thanks,
Chris.
The reason that your page is not refreshed after you submit the form and the redirect is not issued in the browser, is that you are submitting the request over AJAX. This is a request issued by the browser behind the scenes.
If you want to submit the form and for the page to be refreshed, I'd recommend changing your code from Ajax.BeginForm(... to Html.BeginForm(... and then it will load the page and perform the redirect as expected.
I am not quite sure how your ajax calls are structured, but if you are using the MVC Ajax helper you can just call `location.reload(); in the OnComplete method, like so:
#using (Ajax.BeginForm(new AjaxOptions{OnComplete = "javascriptfunction"}))
{
//Data and submit button
}
<script>
function javascriptfunction(){
location.reload();
}
</script>
Say I have the following button
<button id="CopyUsersRolesButton" type="button" onclick="CopyUsersRoles()" data-url="#Url.Action("CopyUsersRoles", "Index", new {userId = "0" })">
Copy Users Roles</button>
I want to redirect to a view that is returned by the following action:
public ActionResult CopyUsersRoles(int userId)
{
var model = new CopyUsersRolesViewModel
{
SelectedUserId = userId
};
return View(model);
}
I need to pass a javascript variable (SelectedUserId) to the action.
The only way I've got it to work is by keeping a placeholder in the URL.Action method and replacing it as follows:
function CopyUsersRoles() {
var url = $('#CopyUsersRolesButton').data('url');
window.open(url.replace('0', SelectedUserId));
return false;
}
This feels very hacky to me, is there not a cleaner solution? I don't currently have a form on the html page and would like to avoid using an input button as all the other buttons have Jquery UI icons (see How to add jQuery UI Button icons to input buttons?).
I have the following code in a partial view
Country Selector</label>
#Html.DropDownListFor(model => model.CountryGroup, Model.CountryCodes, new { id = "CountryGroup", name = "country-codes" })
#Html.ValidationMessageFor(model => model.CountryGroup, "*")
In the controller I have
public ActionResult ProcessRemoteOrder()
{
var a = 1;
return null;
}
I am assuming that when the code runs a break point on var a will be hit. it is not.
Can someone tell me where I can findout what how to get the function in the controller is run?
thnx
If you want to call the controller action when you select an item from the dropdown, you need to listen to the change event of the drop down and use jQuery ajax to make a call to the action method
$(function(){
$("#CountryGroup").change(function(){
$.get("#Url.Action("ProcessRemoteOrder","YourControllerName")",
function(data){
//do some thing with the response, in data variable.
});
});
});
To check whether it is running. Set a breakpoint in your code on the line you want to debug and when the code execute that line the breakpoint will be highlighted with yellow color.
I have a view with a drop down list. The default value for this is stored in a session variable. However, the user change change this, in which case new data is entered.
I have a change handler on the drop down:
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedID,
new SelectList(Model.SelectValues, "Key", "Value",
Model.SelectedID), "", new { onchange = "this.form.submit()" });
... more fields ...
<input type="submit" name="Save" />
}
[HttpPost]
public ActionResult Index(ViewModel vm)
{
... decide if I update my data or save the changes ...
}
I tried wrapping the select in a separate form tag, but then the value of my SelectedID not updated in my view model.
How can I determine when the form is posted from a drop down change, and when it is posted from a button click?
If you don't want to reload the entire page when the user changes the selection of the dropdown you could use AJAX to silently trigger a request to a different controller action that will do the necessary updates. For example:
#Html.DropDownListFor(
model => model.SelectedID,
new SelectList(Model.SelectValues, "Key", "Value"),
"",
new {
id = "myddl",
data_url = Url.Action("update")
}
)
and then in a separate javascript file:
$(function() {
$('#myddl').change(function() {
var form = $(this).closest('form');
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: form.serialize(),
success: function() {
alert('update success');
}
});
});
});
and finally you could have a controller action responsible for the update:
[HttpPost]
public ActionResult Update(ViewModel vm)
{
... this will be triggered everytime the user changes some value in the
droipdown list
}
The simplest way would be to simply attach some behavior to those element's events and set a hidden field with the event target (which by now, should sound very familiar to __EVENTTARGET).
Like so:
$('#someButton').click(function()
{
$('#someHiddenField').val('someButton');
});
$('#someDropDown').change(function()
{
$('#someHiddenField').val('someDropDown');
});
And then your action method could inspect this value and act appropriately.
HOWEVER
It sounds like you're thinking in an outmoded concept for MVC. If you really needed some new information, you should consider using some Ajax and then having one of your action methods return a partial view if you want to update part of the page.
My controller action is being executed twice. Fiddler shows two requests and responses, and for the first one has an icon that indicates "Session was aborted by the client, Fiddler, or the Server."
But I can't figure out where this is happening, or why.
Here are the specifics:
I have a section of a view (ThingFinancials) that looks like this:
#{ using (Html.BeginForm("ConfirmThing", "Thing", null, FormMethod.Get, new { id = "frmGo" }))
{
#Html.HiddenFor(model => model.ThingID)
<button id="btnGo">
Thing is a Go - Notify People</button>
}
}
The javascript for btnGo looks like this:
$("#btnGo").click(function () {
var form = $("#frmGo");
form.submit();
});
The action (stripped down) looks like this:
public ActionResult ConfirmThing(int thingID)
{
[do some database stuff]
[send some emails]
var financials = GetFinancials(thingID);
return View("ThingFinancials", financials);
}
The only thing that looks unusual to me is that the URL you'd see would start out as [Website]/Thing/ThingFinancials/47, and after submission the URL would be [Website]/Thing/ConfirmThing?ThingID=47.
(If you're wondering why the Action name doesn't match the View name, it's because there are multiple form tags on ThingFinancials, and they can't all have the same action name.)
Is there a Server.Transfer happening behind the scenes, or something like that?
If you are using a submit button then you need to cancel the default behaviour when submitting with javascript, otherwise you will submit it twice. Try this:
$("#btnGo").click(function () {
var form = $("#frmGo");
// event.preventDefault(); doesn't work in IE8 so do the following instead
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
form.submit();
});
Your int thingID is a query string parameter that stays with the request. At the end of ActionResult ConfirmThing(int thingID), all you're doing is returning a view. If you'd rather see the clean URL ([Website]/Thing/ThingFinancials/47) you can make the following changes.
public ActionResult ConfirmThing(int thingID)
{
[do some database stuff]
[send some emails]
// This logic is probably in the 'ThingFinancials' action
// var financials = GetFinancials(thingID);
// I'll assume we're in the same controller here
return RedirectToAction("ThingFinancials", new { thingID });
}
This is because of your jquery event just add stopImmediatePropagation() to your jquery event.
$("#btnGo").click(function (event){
event.stopImmediatePropagation();
});