julianc julianc - 5 months ago 11
Javascript Question

Passing value of an onclick event to the controller

I have a button that triggers a "delete" event. This event updates a db entry through a stored proc in case the user decides to continue. However, users can only mark a location as closed (they cannot revert back to open). The default value of a location is declared as string status="1" for open (and as a varchar(1) equaling '1' in the stored proc). If the status is "0" it means the location is closed.

My question is...how can I make it so that the event reflects the change in my controller that handles the update? Does it matter that the variable is declared as a string?

button:

<button type="submit" name="RemoveAccount" id="RemoveAccount" onclick="Confirm_delete()" value="@Model.Location.status">Remove</button>


JS:

function Confirm_delete()
{
return confirm('Are you sure you want to remove this entry?');
};

Answer

Just add an if to your function:

function Confirm_delete(el) {
    if (el.value === '1') {
        el.value = '0';
        return confirm('Are you sure you want to remove this entry?');
    }
    return false;
}

As @Alex mentioned in the comments, do change the onclick to return Confirm_delete(this). Note I also added this as an argument to be clear we want to get a reference to the button.

Note that since the button you have has type="submit" the button should submit the form, which will cause the server to get involved. If you've mapped your model correctly, the value of @Model.Location.status should change to "0" by the time the page rerenders.