GSR GSR - 5 months ago 57
jQuery Question

MVC read label value and pass to controller on button click

I have an MVC razor view with partial views on it. Upon button click in the main view I have to trigger a controller action. I need to pass a

label
value to this action. So I thought I could just get the label value using jQuery after all the HTML is populated. This
label
is in a partial view and my script is in the main view. I keep getting an empty value in alerts, even after the page is fully loaded. Here is the code I have used:

<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);
}
});


Label code in the partial view:

<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>


Is there any other way to achieve this? Please input any ideas.

Answer

The following worked for me:

Before Click (Edit):

BeforeClick

On Click (Edit):

OnClick

Post Click Url (Edit):

PostClick

View (Index):

<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>

Partial View with Edit (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>

Model:

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

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

Controller with Index Action Method:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        Product product = new Product() {HistoryDO = new History(){MACSerial = "TestSerial"} };
        return View(product);
    }
}

HistoryLookup Controller:

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