2016-11-17 60 views
-1

我在.cshtml文件中有下面的一段代碼。無法在視圖上動態顯示標籤標籤

<div class="row"> 

      <input type="text" placeholder="Enter POR ID" id="porID" class="col-md-2 input-sm" name="porTextBox"> 
      <button class="btn btn-primary col-md-2 btn-sm" style="margin-left:15px;width:150px;" type="submit" id="btnCreateTFSItems"><strong>Create TFS Items</strong></button> 
      @if (TempData["formState"] != null) 
      { 
       //@Html.Label("lblsuccess", "Successfully created TFS Work Items!") 
       <label id="lblsuccess" style="color:green; visibility:visible"> Successfully created TFS Work Items!</label> 
      } 
     </div> 

和按鈕調用腳本標籤下面的功能:

<script type="text/javascript"> 
$(document).ready(function (e) { 

    $('#btnCreateTFSItems').click(function() { 
     var txt = $('#porID'); 
     var errorLabel = $('#lblError'); 
     if (txt.val() != null && txt.val() != '') { 
      //alert('clicked'); 

      $.ajax({ 
       url: '@Url.Action("CreateWorkItems", "Tables")', 
       type: 'POST', 
       data: { 'porTextBox': $('#porID').val() } 
      }); 
      // alert('Successfully added'); 
     } 
     else { 
      errorLabel.text("Please enter valid PORID"); 
      return false; 
     } 
    }); 

    $("#porID").keypress(function (e) { 
     var errorLabel = $('#lblError'); 
     errorLabel.text(""); 
     //if the letter is not digit then display error and don't type anything 
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 
      return false; 
     } 
    }); 
}); 

的問題是在.cshtml文件,它是檢查的條件,但其不添加標籤。原因可能是因爲頁面不刷新以呈現標籤。我是新的UI開發,所以我嘗試了一些我在網上找到的選項,但無法使其工作。有什麼辦法可以做到這一點?

+0

你是什麼意思_不添加label_?您在'keypress()'方法中將其設置爲空字符串(並且只在輸入爲空的情況下給它一個值) –

+0

我已經嘗試在按鈕標記下方的單獨div中添加標籤,但仍然無法賦值給它。 –

+0

當頁面第一次渲染時,TempData [「formState」]的值是什麼 - 如果它的'null',那麼標籤將不存在。不清楚你試圖在這裏做什麼 –

回答

0

原因可能是因爲頁面不刷新以呈現標籤。

沒錯。您使用JQuery(客戶端腳本)向服務器發送Ajax請求,並期望執行Razor代碼(服務器代碼)以顯示標籤。這不起作用,因爲服務器代碼不知道有關客戶端代碼的任何信息。

解決方案是通過JQuery顯示標籤。默認渲染它,但用CSS隱藏(display:none)。請求成功後,您可以通過使用JQuery將CSS display屬性設置爲「block」或「inline」來顯示標籤。