Bigeyes
Bigeyes

Reputation: 1666

Pass value outside of the BeginForm into it

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

  1. I modified the model AddQuestionModel, Added one more property SelectedLanguage.
  2. 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">&times;</button>
             <h3>Add New Question</h3>
         </div>
         <div class="modal-body">
         @Html.TextBox("SelectedLanguage",new { value = "English", @class = "hidden" })
    
  3. 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

Answers (1)

Pedro S Cord
Pedro S Cord

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:

  • Form Data
  • Route Data
  • Query String
  • Files
  • Custom (cookies for example)

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:

Upvotes: 1

Related Questions