2012-11-17 87 views
0

我有一個javascript函數,可以根據DropDown在我的頁面中生成鏈接。我在兩個地方檢查了javascript函數;當DropDown使用屬性「onchange」更改時,以及頁面加載時。當頁面在viewbag上沒有元素的情況下加載時產生錯誤,我的javascript沒有在viewbag上沒有識別出生成鏈接的null元素。查看頁面無法識別負載中的空元素

<p>Pesquisar por: @Html.DropDownList("tipoPesquisa", ViewBag.DropDownPesquisa as SelectList, new { onchange = "alteraFiltro()" }) 



<div id="dadosFornecedor"> 
     @if (ViewBag.CurrentFornecedor != null) 
     { 
      <fieldset> 
       <legend>@ViewBag.CurrentFornecedor.RazaoSocial</legend> 
       <b>Razão Social:</b> @ViewBag.CurrentFornecedor.RazaoSocial <b>Endereço:</b> @ViewBag.CurrentFornecedor.Endereco 
       @Html.Hidden("idFornecedor", new { IdFornecedor = ViewBag.CurrentFornecedor.IdFornecedor }) 
       <input type="button" class="btn" onclick="removerFornecedor();" value="Remover Fornecedor" /> 
       <br /> 
       <br /> 
      </fieldset> 
      <br /> 

     } 
    </div> 


<script type="text/javascript"> 
    $(function() { 

     alteraFiltro(); 
    }); 

    function removerFornecedor() { 
     var div = $("#dadosFornecedor"); 
     var hidden = $("#idFornecedor"); 
     div.empty(); 

     div.append("<input type='hidden' name='deletarFornecedor' value='true' />") 

    } 

     function alteraFiltro() { 
      var urlCodigo = $("#linkCodigo"); 
      var urlLancamento = $("#linkLancamento"); 
      var urlPagamento = $("#linkPagamento"); 
      var urlFornecedor = $("#linkFornecedor") 
      var dropValue = $("#tipoPesquisa").val(); 
      var hidden = $("#idFornecedor"); 

      if (hidden.val() == "" || hidden.val() == null || hidden == null) { 
       urlCodigo.attr("href", "[email protected]&[email protected]&currentDrop=" + dropValue + ""); 
       urlLancamento.attr("href", "[email protected]&[email protected]&currentDrop=" + dropValue + ""); 
       urlPagamento.attr("href", "[email protected]&[email protected]&currentDrop=" + dropValue + ""); 
       urlFornecedor.attr("href", "[email protected]&[email protected]&currentDrop=" + dropValue + "") 
      } else{ 
       urlCodigo.attr("href", "[email protected]&[email protected]&[email protected]&currentDrop=" + dropValue + ""); 
       urlLancamento.attr("href", "[email protected]&[email protected]&[email protected]&currentDrop=" + dropValue + ""); 
       urlPagamento.attr("href", "[email protected]&[email protected]&[email protected]&currentDrop=" + dropValue + ""); 
       urlFornecedor.attr("href", "[email protected]&[email protected]&[email protected]&currentDrop=" + dropValue + "") 
      } 

     } 


    </script> 

回答

0

如果問題是由ViewBag.CurrentFornecedor沒有當首次加載視圖的值造成的,試着改變你的JavaScript沿着這些線路:

var hidden = $("#idFornecedor"); 

if (hidden.val() == "" || hidden.val() == null || hidden == null) { 

// ... 

} 
else { 

    urlCodigo.attr("href", "[email protected]&idFornecedor=" 
     + @{ViewBag.CurrentFornecedor != null ? ViewBag.CurrentFornecedor.IdFornecedor : -1} 
     + "&[email protected]&currentDrop=" + dropValue + ""); 

    // ... 

}