2016-11-07 50 views
1

我的MVC控制器中的动作被我的jQuery代码调用了两次。在做了一些调查之后,我发现链接是由jQuery以及MVC视图触发的。动作方法在控制器中被调用两次

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

查看其中的链接被填充

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

,我面临的问题是,当应用程序运行和点击任何正在动态生成的链接后。动作方法第一次运行并填充我的模型,但不是在我的视图中显示动作方法,而是再次点击动作方法,该模型在模型中填充null,因为文本框没有从数据库值绑定。

请帮我解决这个问题。有没有一种方法可以在我的操作结果中访问idhref而不使用jQuery?

+0

你能为''显示'html'吗?treeview-menu li a [name =“environments”]'element? –

+0

听起来你有两个'a [name =“environments”]元素。他们是否有任何机会嵌套? –

+0

添加了我正在使用的视图 –

回答

0

正如你在问题中所述,正在发生的事情是:

  • jQuery的运行正常(但你的代码有问题什么都不做这样的观点)
  • 链接的href的重定向页面到一个新的视图

如果你想获得的页面和不是重定向,您可以:

  • 变化a从事件处理程序的button type=button
  • 返回从事件处理程序假
  • 调用Event.preventDefault()
  • 除去href=(通过改变到一个按钮)
  • 可能变化到#根据其他答案,但这是建议反对,并会有其他方面影响没有上述变化之一。

如果你想重定向(不停留在同一页上),通过在id,就像你说的“不使用jQuery”,然后将@Url.Action使用routeValues过载:

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

您可以扩展new { genericId =以包含您需要的其他模型属性(尽管id应足以对您的操作进行一些更改)。

0

尝试更换@ Url.Action(@ item.Name, “配置”)HREF = “#”

<a href="#" id="@item.GenericMasterId" name="environments"> 

这就是为什么你有2个呼叫控制器,1 jQuery的点击另一1,当您点击链接。