Reputation: 327
I'm having a difficult time passing my Select values on my View to the controller. I have two items on my view which I wish to return to the model, where I can call in the controller. Heres what I have so far.
<label for="phone" class="ui-hidden-accessible">Phone Number:</label>
@Html.TextBoxFor(m => m.PhoneNumber, new { @class = "field-margin", id="phone", type="tel", placeholder="Phone Number"})
<p></p>
<div><p>Save phone for future purchases?</p>
<select name="SavePhone"id ="SavePhone" class="SavePhone" data-role="select">
<option value="false" @(Model.SavePhone == false ? "selected" : "")>No</option>
<option value="true" @(Model.SavePhone == true ? "selected" : "")>Yes</option>
</select><
I'm not exactly sure how to call the second part for the select options. However the top part of my code which accepts the phone number works. My naming in the model, controller, and view all are the same so I'm not sure what to do next. If you have any suggestions it would be appreciated.
Thanks!
Edit
I figured out a part of my problem, Since I am loading this as
@Html.Partial("MobilePhoneView", Model)
after I click continue on the first page, it loads the view with my two options and hits the select block before it even displays. Is there some kind of work around for this?
Upvotes: 0
Views: 1198
Reputation: 56688
The only possible problem with your code might be with selected
attribute. Not all browsers understand just selected
(I believe this is HTML5 way of setting such attributes), though all should understand selected="selected"
. So what you can try is:
<select name="SavePhone"id ="SavePhone" class="SavePhone" data-role="select">
<option value="false" @(Model.SavePhone == false ? "selected=\"selected\"" : "")>No</option>
<option value="true" @(Model.SavePhone == true ? "selected=\"selected\"" : "")>Yes</option>
</select>
Upvotes: 0
Reputation: 9458
You can do this using AJAX. If you have following HTML
<select name="SavePhone"id ="SavePhone" class="SavePhone" data-role="select">
<option value="false">No</option>
<option value="true">Yes</option>
</select>
Then , you can simply use following to sent your choice to controller:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("form").submit(function () {
$.ajax({
url: '@Url.Action("MethodName","ControllerName")',
type: 'POST',
cache: false,
data: { Selected: $("#SavePhone").val() },
success: function (data) {
//
}
});
});
)};
</script>
You will get this value in the controller
private string MethodName (string Selected)
{
String value = Selected;
return "OK";
}
Upvotes: 1