1

我有一個部分視圖的MVC剃刀視圖。在主視圖中單擊按鈕時,我必須觸發控制器操作。我需要將label值傳遞給此操作。所以我想我可以在所有的HTML被填充後使用jQuery獲得標籤值。這label是在局部視圖,我的腳本是在主視圖。即使在頁面完全加載之後,我仍然在警報中獲得空值。這裏是代碼我用:MVC讀取標籤值並通過按鈕單擊傳遞給控制器​​

<input type="button" class="ViewInfo-success" value="View History" onclick="return HistoryResponse()" /> 
function HistoryResponse() { 
    var mac = $('#cmmac').html(); 
    alert("alert1" + mac); 

    try { 
     location.replace('/HistoryLookup/GetHistory' + mac); 
    } 
}); 

標籤代碼在局部視圖:

<div class="col-lg-2"> 
    @Html.Label("MAC Seria:", new { id = "cmmac" }) 
</div> 

<div class="col-lg-2"> 
    @Html.DisplayFor(x => x.HistoryDO.MACSerial) 
</div> 

是否有任何其他的方式來實現這一目標?請輸入任何想法。

+0

什麼是#cmmac元素? –

+0

@RoryMcCrossan我認爲它是元素的標識'@ Html.Label(「MAC Seria:」,new {id =「cmmac」})' – din

+1

是的,編輯後現在有意義。 @OP給出的代碼你的URL會是這樣的:''/ HistoryLookup/GetHistoryMAC Seria:'這看起來不對。什麼是你想要建立的實際URL? –

回答

0

以下爲我工作:

點擊之前(編輯):

BeforeClick

上單擊(編輯):

OnClick

後點擊網址(編輯):

PostClick

視圖(指數):

<input type="button" class="ViewInfo-success" value="View History" onclick="HistoryResponse()" /> 

@Html.Partial("MACSerialPartial") 

<script> 
    function HistoryResponse() { 
     var mac = document.getElementById('cmmac').innerText; 
     alert("alert1" + mac); 
     location.replace('/HistoryLookup/GetHistory?id=' + mac); 
    }; 
</script> 

局部視圖編輯(MACSerialPartial):

@model mvc_read_label_value.Models.Product 

<div class="col-lg-2"> 
    <p>MAC Serial:</p> 
</div> 

<div class="col-lg-2"> 
    <p id="cmmac">@Model.HistoryDO.MACSerial</p> 
</div> 

型號:

public class Product 
{ 
    public History HistoryDO { get; set; } 
} 

public class History 
{ 
    public string MACSerial { get; set; } 
} 

控制器與索引操作方法:

HistoryLookup控制器:

public class HistoryLookupController : Controller 
{ 
    public ActionResult GetHistory(string id) 
    { 
     return View(); // TODO: need to make a view corresponding to this action 
    } 
} 
+0

嗨Bwyn,Thanq爲您的詳細迴應。我需要將macid值'testserial'傳遞給控制器​​。我得到警報eith空cMMac序列:也是我需要該標籤的值'testserial'我如何捕獲? – GSR

+0

請參閱我上面的編輯。 – bwyn

0

所以我不得不這樣做是在模型存儲MACID值像這樣隱藏的領域。

@Html.HiddenFor(x => x.Model.historyDO.MACSerial, new { id = "macId", name = "macId" }) 

按鈕,主視圖

<input type="button" class="ViewInfo btn btn-success" value="View History" onclick="return HistoryResponse()" /> 

在historyresponse()方法,通過隱藏域ID

function HistoryResponse() { 
     var params = '?MacId=' + $("#macId").val(); 
     alert("alert3" + params); [![enter image description here][1]][1] 
     try { 
      location.replace('/HistoryLookup/GetHistory' + params); 
     } 
     catch (exception) { } 
    } 

獲得的價值和POST行動。

[HttpGet] 
public ActionResult GetHistory(string macId) 
{  
var model = Repository.GetHistory(macId); 
return View("HistoryLookupResponse", model); 

} 
相關問題