代码之家  ›  专栏  ›  技术社区  ›  Flufy

从组合框中选择项时显示消息框

  •  -2
  • Flufy  · 技术社区  · 6 年前

    我开始和MVC打交道。

    我需要以下内容:一个组合框,当用户选择其中一个项目时,一个消息框将弹出并显示“请这次工作!!.

    这里是我的代码:

    index.html:

    @Html.DropDownListFor(x => x.SelectedFileName, Model.Files, new { Name = "map", @class = "form-control" })
    

    家庭虚拟机:

    public class HomeVM
    {
        public List<SelectListItem> Files { get; set; }
        public string SelectedFileName { get; internal set; }
        public List<string> DynamicAlgorithems { get; set; }
    }
    

    家庭控制器:

    [HttpPost]
    public ActionResult ShowAllMobileDetails(HomeVM MV)
    {
        string SelectedValue = MV.Files.Count.ToString();
        MessageBox.Show("Please work this time!!!");
        return View(MV);        
    }
    

    问题是:我可以看到组合框中的所有项,但当用户选择其中一项时,不会弹出消息框。

    你知道我错过了什么吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   marc_s    6 年前

    你不能 MessageBox.Show 在ASP.NET MVC中,它用于 winform .

    集合 id='SelectedFileName' OnChange 事件。使用JS alert 功能

    你可以用JS来完成。

    这是jquery示例。

    $('#SelectedFileName').change(function(){
       alert('Please work this time!!!');
    });
    

    $('#SelectedFileName').change(function(){
       alert('Please work this time!!!');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <select id="SelectedFileName">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

    或者在你的问题上,你可以约束 onchange 直接在DropDownList中的事件。

    @Html.DropDownListFor(x => x.SelectedFileName, Model.Files, new { Name = "map", @class = "form-control" , onchange = @"alert('Please work this time!!!')"})
    

    编辑

    这里是一个带有ASP.NET小示例的Ajax。

    1. 在中包含jquerylib Razor 页面(HTML页面)

      <script
           src="https://code.jquery.com/jquery-2.2.4.js"
           integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
           crossorigin="anonymous"></script>
      
    2. 结合 Onchange 事件 id='selectedFileName' 下拉列表。

    3. 使用 post 方法执行Ajax调用,并使用第三个参数回调函数获取 MVC 结果。

    像这样,你可以在 ShowAllMobileDetails 行动。

    $('#SelectedFileName').change(function(){
       //get id="SelectedFileName"
       $.post('Home/ShowAllMobileDetails', $("form").serialize(),function(data){
            alert(data);
       });
    });
    
    [HttpPost]
    public ActionResult ShowAllMobileDetails(HomeVM MV)
    {
        string SelectedValue = MV.Files.Count.ToString();
        // your logic
    
        string result = "Please work this time!!!";
        return View(result);        
    }