0

I have a view in which users enter their primary phone number and then their mobile number and selects a radio button on which number he prefers to be contacted on.

this is my code....

 /*<div class="form-group col-md-3">
    @Html.Label("First Name")
    @Html.TextBoxFor(m => m.FirstName)
 </div>
 <div class="form-group col-md-3">
     @Html.Label("Last Name")
     @Html.TextBoxFor(m => m.LastName)
 </div>*/
 <div>
      @Html.Label("Primary Number")
      @Html.TextBoxFor(m => m.PrimaryNumber)
      @Html.RadioButtonFor(m => m.Contact, null)
 </div>
 <div>
      @Html.LabelFor(m => m.Mobile)
      @Html.TextBoxFor(m => m.Mobile)
      @Html.RadioButtonFor(m => m.Contact, null)
</div>

And this is my Model (simplified)

Public class Customer{
    //public string FirstName { get; set; }
    //public string LastName { get; set; }
    public string PrimaryNumber { get; set; }
    public string Mobile { get; set; }
    public string Contact { get; set; }
}

My problem is like this, how to I set the string value of the radio button to the input of the customer in the appropriate text box (in order for me to set it to the "Contact" property in my model)

1 Answer 1

1

You could change the type from string to int and provide a value for each RadioButton:

 @Html.RadioButtonFor(m => m.Contact, 1)
 @Html.RadioButtonFor(m => m.Contact, 2)

Or if you want to use a string:

 @Html.RadioButtonFor(m => m.Contact, "L")
 @Html.RadioButtonFor(m => m.Contact, "M")

By the way, this question has been already answered a google times, here are a couple of them:

RadiobuttonFor in Mvc Razor syntax

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

Sign up to request clarification or add additional context in comments.

2 Comments

is there any way to set the value dynamically for example @Html.RadioButtonFor(m => m.Contact, "222 222 2222" (based on the input) in order not have to do extra processing if (1) blah; if (2) blah....
It is possible using javascript or a custom binding but is it worth the effort? If the user inputs two telephone numbers you will only save the preferred telephone into the database? What's the point of asking for two numbers then? You should have three fields in the database, Telephone, Mobile and PreferredContact and then you just save everything and when someone has to call this user they will see in the screen all telephone numbers and some way to indicate which one is the preferred one so they will try first with this number and if they don't answer, the other one, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.