0

I have a problem with using @Html.DropDownListFor element.

What i have:

Model 'DatabaseModel':

public class DirectionEntity
{
    public string Id { get; set; }
    public string DirectionName { get; set; }
}
public class ViewModel
{
    public int SelectedDirectionID { get; set; }
    public List<DirectionEntity> DirectionList { get; set; }
}

Model 'DataFactory':

public class DataFactory
{
    public static ViewModel Refresh()
    {
        using (var db = new MyDatabase())
        {
            return new ViewModel()
            {
                DirectionList = db.Directions.Select(_ => new { _.Id, _.DirectionName })
                    .ToList()
                    .Select(_ => new DirectionEntity() { Id = _.Id.ToString(), DirectionName = _.DirectionName })
                    .ToList(),
            };
        }
    }
}

Controller:

    public System.Web.Mvc.ActionResult AddNewDocument()
    {
        var db = DataFactory.Refresh();
        return View(db);
    }

   [HttpPost]
    public System.Web.Mvc.ActionResult AddNewEntry(ViewModel m)
    {
            m = DataFactory.Save(m);
            ModelState.Clear();
            return View(<some view>);
    }

View:

@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.SelectedDirectionID, new     SelectList(Model.DirectionList.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.DirectionName }), "Value", "Text"), new { @class = "Duration", required = "required" })
<button type="submit" class="btn btn-default SaveAll">Save</button>
}

The question: How to handle 'SelectedDirectionID' value, after user selected some position on dropdownlist, but not yet sent the request to the server using a POST-method.

Dmitry K
  • 13
  • 4

2 Answers2

3

See what the id of your dropdown is and then you can subscribe to the change event on the client side. You can do this using jQuery.

$("#idOfYourDropDown").change(function () {
    // Do whatever you need to do here
    // Here are some ways you can get certain things
    var end = this.value;
    var selectedText = $(this).find("option:selected").text();
    var selectedValue = $(this).val();
    alert("Selected Text: " + selectedText + " Value: " + selectedValue);
});

Also you should see my answer here on why you should not return a view from a POST action the way you are.

Community
  • 1
  • 1
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
0

In this case you have to use Jquery. As per your view id for your drop down is 'SelectedDirectionID';

Your Js:

 $(document).ready(function () {
            var selectedValue = $('#SelectedDirectionID').val();
            var selectedText = $("#SelectedDirectionID option:selected").text();
        });

Or Inside drop down change event.

 $('#SelectedDirectionID').change(function () {
                var selectedValue = $(this).val();
                var selectedText = $(this).find("option:selected").text();
            });
Anadi
  • 744
  • 9
  • 24