So I want to do something almost exactly like you find here: http://www.makeitspendit.com/calling-asp-mvc-controllers-from-jquery-ajax/
It will do exactly what I want it to do, but having the same script written out for all 4 buttons is not very DRY. (Well, not DRY at all)
I would like to have one script to call the correct view based on the ID of the button, so that code would only have to be on my page once.
I tried passing this.id into the function call, and using concatenation in the "url:" property of the ajax call but that doesn't work.
EXAMPLE:
<div id="projectDiv">
<button onclick="loadProject(this.id)" id="_Project1">Project 1</button>
<button onclick="loadProject(this.id)" id="_Project2">Project 2</button>
<script>
function loadProject(projectID) {
$.ajax({
url: ("/Projects/Project/"+projectID),
datatype: "text",
type: "POST",
success: function (data) {
$('#projectDiv').html(data);
},
});
});
</script>
And in the controller:
[HttpPost]
public ActionResult Project(string id)
{
return View(id);
}
I've searched all over for this and found similar things (but not similar enough to derive what I need) but couldn't find this scenario -- which I would've assumed was common enough to have more information.
The example code illustrates how I would LIKE it to work, but I can't seem to pass the variable into the url property like that. While I am admittedly pretty new to ASP.NET MVC, this seems like it should be pretty basic and yet I've been stuck on this for a minute.