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

在mvc中将数据从视图传递到控制器

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

    鉴于我有一个DropDownList,当选择了某个从控制器调用函数的项时,

    我在试着 pass参数 从视图中在控制器中运行。

    我只需要从index.html调用homecontroller.cs中的函数,而不需要参数,现在只需要传递一些字符串。

    我现在的代码:

        **Index.cshtml:**
    
    @using (Ajax.BeginForm("nMap", "Home", new AjaxOptions
    {
        HttpMethod = "Get",                                              
        InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace
    }))
    {
       @Html.DropDownListFor(x => x.SelectedFileName, Model.Files, new { Name = "map", @class = "form-control", onchange = "CallChangefunc()" })
    }     
    .
    .
    .
    <script type="text/javascript">
       function CallChangefunc() {
        window.location.href = '@Url.Action("nMap", "Home")';
       }
    </script>
    

    霍姆夫姆:

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

    家庭控制器.cs:

    .
    .
    .
     [ActionName("nMap")]
     public ActionResult NMap()
     {
    
          //some code
            return RedirectToAction("Index");
     }
    

    我所需要的是:

    Index.cshtml:

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

    家庭控制器.cs

    [ActionName("nMap")]
    public ActionResult NMap(string someStringParam)
    {
     //do something with the param
    }
    

    我该如何实现?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Paul Swetz    6 年前

    改变

    [ActionName("nMap")]
    public ActionResult NMap(string someStringParam)
    {
     //do something with the param
    }
    

    [ActionName("nMap"),HttpGet]
    public ActionResult NMap(SelectListItem SelectedFileName)
    {
     //do something with the param
    }
    

    mvc使用命名约定来排列参数映射。

    阿尔索

    改变

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

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

    彻底摆脱JavaScript。

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

    应该是

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