I've created an ASP.NET MVC 2.0 application.
I have a dropdownbox with a list of “reports”. Next to the dropdown, I have two ActionLink. One that says “Add new report” and the other one say “Edit report”.
The “Add new report” link, is pretty straightforward … it calls a ViewResult in my Controller and returns a new View()
. Great! this works no problem!
The “Edit report” link is a bit trickier since I wish to pass the selected ID of the item currently selected inside the dropdown to the ActionLink.
I've found an article that shows me how to AJAXify my ActionLink but I’m doing something wrong…
Here is the ActionLink in the View for the “Edit” link:
<%=Html.ActionLink("Edit report", "EditReport", "Report", null, new { id = "edit" })%>
Here is the jQuery click event to handle the “click”
$("#edit").click(function() {
$.ajax({
url: '<%=Url.Action("EditReport")%>',
type: 'POST',
data: { reportId: $('select[name="ReportId"] option:selected').val() },
success: function(result) {
//alert("succes");
},
error: function() {
alert("error");
}
});
return false;
});
Here is the method in the Controller:
public ViewResult EditReport(int reportId)
{
return View("EditReport");
}
When placing a breakpoint in the Controller’s method, it gets hit and the parameter “reportId” is correctly passed…but the rest of the code (return View() portion) does not seem to work because inside the jQuery click event, I have a “return false”.
When removing the “return false” inside the click event, the breakpoint no longer gets hit. Thus, I can't go to my “EditReport” view…
What am I missing/not understanding here?
Also … is there a better/nicer/cleaner approach to achieve my task without having to use an AJAX call?
Ok, since I now can post the answer here it is (if anyone is interested):
First, I needed to modify the ActionLink and put in a predefined value for the parameter which will be replaced once the link is clicked.
<%=Html.ActionLink("Edit report", "EditReport", "Report", new { reportId="xxx"}, new { id = "edit" })%>
Second, modify the jQuery click event:
$("#edit").click(function() {
//Get the id of the selected item in dropdown
var id = $('select[name="ReportId"] option:selected').val();
//Replace the predifined QueryString param "xxx" with the "id"
this.href = this.href.replace("xxx", id);
});
Nothing changes in the Controller’s method…it stays the same:
public ViewResult EditReport(int reportId)
{
//Fix me...
return View("EditReport");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With