ASP.NET MVC html.dropdownlistfor:如何处理选定的ID



我在使用 @html.dropdownlistfor element。

我拥有的:

模型'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; }
}

模型'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(),
            };
        }
    }
}

控制器:

    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>);
    }

查看:

@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>
}

问题:在用户在下拉列表上选择某个位置后,如何处理'SelectedDirectionID'值,但尚未使用后方法将请求发送到服务器。

查看下拉列表的ID是什么,然后您可以在客户端订阅change事件。您可以使用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);
});

还应该在这里看到我的答案,说明为什么您不应该按照自己的方式从邮局返回视图。

在这种情况下,您必须使用jQuery。按照您的视图ID,下拉列表为" selectedDirectionId";

您的JS:

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

或内部下拉截止更改事件。

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

最新更新