0

I use in my Razor View the following ViewModel.

public class EditionStatusReservation
{
    public Reservation Reservation { get; set; }

    [Display(Name = "Status:")]
    public IEnumerable<SelectListItem> States { get; set; }
}

The class Reservation looks like this:

public class Reservation
{
    [Display(Name = "Status:")]
    [Required]
    [MinLength(3), MaxLength(15)]
    public string Status { get; set; }
}

In my Razor view when I click submit button I would like to assign to variable Status new value using javascript. So far I created something like this.

$(function () {
    $("form").submit(function () {
        var selTypeText = $('select[name="SelectReservationState"]').val();
        $("#Reservation.Status").val(selTypeText);
    });
});

This solution is not proper. How can I access to field named Status to set its value?

Section with dropdownlist where item to assign is taken.

<div class="form-group">
    @Html.LabelFor(model => model.States, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("SelectReservationState", Model.States, new { id = "SelectReservationState" })
    </div>
</div>
adiga
  • 34,372
  • 9
  • 61
  • 83
maciejka
  • 818
  • 2
  • 17
  • 42
  • Why are you doing that instead of binding to your model? And show your view code for the ` –  Sep 04 '17 at 09:26
  • I use binding my model, but in debugger it shows me old value not new. When I make request then I bind model Reservation which is a part of EditionStatusReservation. – maciejka Sep 04 '17 at 09:30
  • Change your view code to `@Html.DropDownListFor(m => m.Reservation.Status, Model.States)` and delete your script. –  Sep 04 '17 at 09:30
  • 1
    But view models should not contain data models. Delete the `Reservation` property and add `public int SelectedStatus { get; set; }` (or `string` as required) plus the other properties of `Reservation` you need in the view. Refer [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) and then its `@Html.DropDownListFor(m => m.SelectedStatus, Model.States` –  Sep 04 '17 at 09:31
  • And you add the `[Display]` attribute to the property your binding to, not the `SelectList` - so its `@Html.LabelFor(m => m.SelectedStatus)` (your not even creating a label associated with the form control with your current code) –  Sep 04 '17 at 09:34

0 Answers0