Change onclick method in mvc submit button

238 views Asked by At

I have a submit button where I want to change the onclick method based on CurrentGroupName And I bring CurrentGroupName from ViewBag.

So here is the code if

CurrentGroupName = O&M Fiber Engineer I want onclick="return SaveFiberInfofttx('Approve');" method to enable.

And if

CurrentGroupName = O&M Fiber Lead I want onclick="return FiberLeadRejValidation_FTTX('Approve');" method to enable.

Here is my button code.

<input type="button" id="btnRemarksSubmitFLFTTX" class="button submit" value="@((ViewBag.CurrentGroupName == "O&M Fiber Lead") ? Html.Raw("Accept") : Html.Raw("Approve"))">

2

There are 2 answers

2
Mikhail On BEST ANSWER

You can construct the required button attributes within a separate code block in the following manner:

Controller:

public ActionResult Index() {
    //ViewBag.CurrentGroupName = "O&M Fiber Lead";
    ViewBag.CurrentGroupName = "O&M Fiber Engineer";
    return View();
}

View:

@{ 
    string buttonText = string.Empty;
    string onClickHandler = string.Empty;
    if (ViewBag.CurrentGroupName == "O&M Fiber Lead") {
        buttonText = "Accept";
        onClickHandler = "return FiberLeadRejValidation_FTTX('Approve');";
    } else if (ViewBag.CurrentGroupName == "O&M Fiber Engineer") {
        buttonText = "Approve";
        onClickHandler = "return SaveFiberInfofttx('Approve');";
    }
}

<script type="text/javascript">
    function FiberLeadRejValidation_FTTX(arg) {
    }
    function SaveFiberInfofttx(arg) {
    }
</script>

@using (Html.BeginForm()) {
    <input type="submit" value="@buttonText" onclick="@onClickHandler">
}
2
Muhammad Zeeshan On

You can using the following code:

@{
    string currentGroupName = ViewBag.CurrentGroupName;
    string onClickMethod = "";
    if (currentGroupName == "O&M Fiber Engineer")
    {
        onClickMethod = "return SaveFiberInfofttx('Approve');";
    }
    else if (currentGroupName == "O&M Fiber Lead")
    {
        onClickMethod = "return FiberLeadRejValidation_FTTX('Approve');";
    }
}
<button type="submit" onclick="@onClickMethod">Submit</button>

One thing to keep in mind is that the value of ViewBag.CurrentGroupName should match exactly with the value "O&M Fiber Lead" (including upper/lower case). If the value doesn't match, the button will display "Approve" instead of "Accept".