JQuery ActionLink Option

I created an ASP.NET MVC 2.0 application.

I have a dropdownbox with a list of "reports". Next to the dropdown, I have two ActionLinks. One that says β€œAdd a new report,” and the other says β€œEdit a report."

The "Add a new report" link is pretty simple ... it calls ViewResult in my controller and returns new View() . Large! It's not a problem!

The Edit Report link is a little more complicated, because I want to pass the selected identifier of the item selected in the drop-down list to ActionLink.

I found an article that shows me how to AJAXify my ActionLink, but Im doing something wrong ...

Here is the ActionLink link in the view for the Edit link:

 <%=Html.ActionLink("Edit report", "EditReport", "Report", null, new { id = "edit" })%> 

Here is the jQuery click event for handling "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 you place a breakpoint in the Controllers method, it gets in and the "reportId" parameter is passed correctly ... but the rest of the code (return View ()) does not work, because inside the jQuery click event, I have "return false".

When you delete "return false" inside the click event, the breakpoint no longer hits. Thus, I cannot go to my view of "EditReport" ...

What am I missing / do not understand here?

Also ... is there a better / nicer / cleaner approach to accomplishing my task without using an AJAX call?

+4
source share
2 answers

Good, since now I can post the answer here (if anyone is interested):

First, I needed to change the ActionLink and set a predefined value for the parameter, which will be replaced after clicking the link.

 <%=Html.ActionLink("Edit report", "EditReport", "Report", new { reportId="xxx"}, new { id = "edit" })%> 

Second, change 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 Controllers method ... it remains the same:

 public ViewResult EditReport(int reportId) { //Fix me... return View("EditReport"); } 
+18
source

You can do something similar if you configured a route route for ControllerName / EditReports / {ReportId}

 $("#edit").click(function() { window.location.href = '<%=Url.Action("EditReport")%>' +'/'+ $('select[name="ReportId"] option:selected').val(); return false; }); 
0
source

All Articles