Prashant Kumar Prashant Kumar - 1 year ago 105
jQuery Question

action method is being called twice in the controller

The action in my MVC controller is being called twice from my jQuery code. After doing some investigation I found that the link is being triggered by jQuery as well as from the MVC view.

$('.treeview-menu li a[name="environments"]').on("click", function () {
var genericId = $(this).attr('id');
if (genericId != undefined) {
type: "GET",
url: "/Configuration/Development",
data: { 'genericId': genericId } ,
datatype: "application/json",
success: function (data) { }
else {

public ActionResult Development(DashBoardViewModel model, string genericId)
ViewBag.EnvironmentType = "Development";
DeploymentConfiguration_DAL _deploymentDal = new DeploymentConfiguration_DAL();
model.Configuration = _deploymentDal.FetchDeploymentConfigurationByEnvironmentID(Convert.ToInt32(Convert.ToInt32(genericId)));
if (model.Configuration != null)
return View("Index", model);
return View("Index");

View where the links are being populated

<a href="#"><i class="fa fa-circle-o"></i> Deployment Environment</a>
<ul class="treeview-menu">
@foreach (var item in ViewBag.Environments)
<a href="@Url.Action(@item.Name,"Configuration")" id="@item.GenericMasterId" name="environments">
<i class="fa fa-circle-o"></i>

The problem that I am facing is when the application runs and after clicking on any of the links that are being dynamically generated. The action method runs the first time and populates my model, but instead of displaying it in my view the action method is being hit again which populates
in the model because of which the text boxes are not being bound from the db values.

Please help me in getting this resolved. Is there a way that I can access the
value for
in my action result without using jQuery?

Answer Source

As you've described in the question, what is happening is:

  • the jquery runs fine (but your question code does nothing with the view)
  • the link on the href the redirects the page to a new view

If you want to get the page and not redirect, you can:

  • change the a to a button type=button
  • return false from the event handler
  • call event.preventDefault() from the event handler
  • remove the href= (by changing to a button)
  • possibly change to a # as per other answer, but this is advised against and will have other side affects without one of the above changes as well.

If you want to redirect (not stay on the same page), passing in the id, as you say "without using jquery" then change the @Url.Action to use the routeValues overload:

<a href='@Url.Action(item.Name, "Configuration", new { genericId = item.GenericMasterId })' ... />

You can extend the new { genericId = to include your other model properties that you need (though id should be enough with some changes to your action).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download