SgtOVERKILL
SgtOVERKILL

Reputation: 319

How to get the value from an input in my codebehind while using @keyup

I have an input box that the user types a phone number and it formats it for them.

<label>Primary Phone Number</label><input type="text" class="form-control" id="primaryPhone" placeholder="Primary Phone Number" v-model="primaryPhone" maxlength="12" @keyup="formatPhone" />

I have my formatting for the phone number below using Vue.js.

formatPhone: function (event) {
    if (['Arrow', 'Backspace', 'Shift'].includes(event.key)) {
        this.preventNextIteration = true;
        return;
    }
    if (this.preventNextIteration) {
        this.preventNextIteration = false;
        return;
    }

    if (this.step === 4 && event.target.id === 'primaryPhone') {
        var a = this.primaryPhone.replace(/-/g, '').match(/(\d{1,10})/g)[0];

        this.primaryPhone = a.replace(/(\d{1,3})(\d{1,3})(\d{1,4})/g, '$1-$2-$3');
    }
}

My submit button then runs my btnSubmit function on the code behind like so

<button  id="submit" v-show="agreement === true" class="btn" runat="server"  onserverclick="btnSubmit" style="float:right">Submit</button>

I need to get the value of the input box in my C# code behind. I know that I cannot use runat="server" because this will throw the server tag is not well formed with the @keyup. So I tried to get my value in C# using Request["primaryPhone"] or Request.Form["primaryPhone"] and neither worked. Both said that the object was undefined. How can I get my value in the code behind while using my validation?

I thought about using a hidden field running at the server and just setting that value to the value of my input as a last resort. I feel like there might be a simpler way though.

Upvotes: 0

Views: 67

Answers (1)

Radu Diță
Radu Diță

Reputation: 14191

You aren't setting a name for your input. Try this

<input type="text" class="form-control" id="primaryPhone" name="primaryPhone" placeholder="Primary Phone Number" v-model="primaryPhone" maxlength="12" @keyup="formatPhone" />

Why does the name param matters ?

When the browser makes an HTTP request because of a form submit

  • it looks at all input descendants that are not disabled.
  • after that, depending on the type of input (text, radio, checkbox) it gets their value.
  • when making the request it needs to fill in a list of key, value pairs (this actually depends on the enc type). The key for each input is the value of the name attribute and not the id.

Upvotes: 2

Related Questions