Reputation: 1666
I have a BeginForm to populate all properties of the model. Then I use the property values to pass the action method(Model binding).
Now I have a drop down outside of the BeginForm, I want to add one more property to the model. The property value is picked up from the selected value from the drop down.
So
AddQuestionModel
, Added one more property SelectedLanguage
.Added a hidden textbox inside the BeginForm.
@using (Html.BeginForm("AddSurveyQuestion", "Country", FormMethod.Post, new { enctype = "multipart/form-data", id = "AddQuestionForm" }))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add New Question</h3>
</div>
<div class="modal-body">
@Html.TextBox("SelectedLanguage",new { value = "English", @class = "hidden" })
Listen the change event.
$("#Model_SelectedLanguage").change(function () {
var selectedValue = $(this).find('option:selected').text();
$("#SelectedLanguage").val(selectedValue);
location.reload();
});
Now the question is that I still can't get the select value in the action method
[HttpPost]
public ActionResult AddSurveyQuestion(AddQuestionModel model)`.
I mean model.SelectedLanguage = null
.
Also I found the input element rendered by the TextBox is not hidden at all.
Upvotes: 1
Views: 586
Reputation: 1359
For building hidden field you can use
@Html.Hidden("SelectedLanguage", "english")
or
@Html.HiddenFor(x => x.SelectedLanguage)
The model bidding searches a value in:
Certify that the value of SelectedLanguage
in the AddQuestionModel
is a string and it should work.
If the model binder can find the value and converted or mapped properly it will work.
In case the pages model view is different from the action method you have 3 options:
Build a custom model binding, for more info on this one
https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding
Upvotes: 1