Search code examples
asp.net-mvcasp.net-mvc-4model-view-controllerviewbag

Change onclick method in mvc submit button


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


Solution

  • 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">
    }