将数据从视图传递到MVC中的控制器

时间:2018-07-20 17:22:53

标签: c# asp.net-mvc

在视图中,我具有DropDownList,当选择了某个从控制器调用功能的项目时,

我正在尝试传递参数以从视图在控制器中起作用。

我所拥有的就是我可以从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>

HomVM:

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

Homecontroller.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+")" })

Homecontroller.cs

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

我该如何实现?

1 个答案:

答案 0 :(得分:2)

更改

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

TO

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