I am pretty new to MVC and JavaScript. I have a dropdown ('ProcessGroupRevisions') on a View and when the user selects a certain item in the drop down, I want to execute an action in a controller that will render a new view. I have the following code which is sort of stubbed out. But I know it's not right (because it doesn't work), but I'm not sure what I need to do to make it work.
// This handles the onchange for the Revisions dropdown.
$("#ProcessGroupRevisions").change(function () {
if ($("#ProcessGroupRevisions").prop("value") == "-1") {
'@Url.Action("AddNewRevision", "SetpointManagement", new RouteValueDictionary { { "processGroupId", ViewBag.ProcessGroupId } })';
}
});
$(function() { ValidatefuneralDate(); }); this will get invoked when the DOM is ready. $(document). on("pageload",function(){ ValidatefuneralDate(); });
The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page. A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.
JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.
You can try to use the jquery load method:
$('#yourContainer').load('/ControllerName/ActionName');
"yourContainer" must in this case be the ID of the HTML element which you want to use as a container for your view. You may also want to have some extra logic to avoid having that hard-coded URL to the controller there. In that case you can do something like this:
var baseUrl = '@Url.Content("~")'
$("#yourContainer").load(baseUrl + "ControllerName/ActionName");
Note that the baseUrl variable must be defined in your CSHTML file and not in a separate js file, because it must be handled on the server-side.
Sorry posted accidentally before I was finished the first time.
<script>
$(function(){
$("#ProcessGroupRevisions").change(function () {
if ($("#ProcessGroupRevisions :selected").val() == "-1") {
var url = '@Url.Action("AddNewRevision", "SetpointManagement")';
//To load the view via AJAX
$("#GroupRevisionDetails").load(url, new {processGroupId: $("#ProcessGroupRevisions :selected").val()});
//To load the view and replace the current page
window.location.href = url + "?processGroupId=" + $("#ProcessGroupRevisions :selected").val();
}
});
});
</script>
<select id="ProcessGroupRevisions">
<option value="-1">-- Pick One --<option>
<option value="1">Group Revision 1<option>
<option value="2">Group Revision 2<option>
<option value="3">Group Revision 3<option>
<option value="4">Group Revision 4<option>
</select>
<div id="GroupRevisionDetails"></div>
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