【问题标题】:How to pass enum value to controller with ajax?如何使用ajax将枚举值传递给控制器​​?
【发布时间】:2015-05-25 11:29:17
【问题描述】:

我想将我的枚举值传递给控制器​​。

我的模型中有这个枚举:

public enum Section
{
      Upper,
      Lower
};

我想通过控制器上的 ajax 传递这个值:

$(function () {
  var section='@Section.Upper'//i want to pass Upper value only to my controller.
  alert(section) ///output Upper
 $.ajax({
                url: '/Section/FindSection',
                data: { 'Section': section},
 });

在数据库表中,它存储 1 为上,0 为下。

我的控制器:

public ActionResult Generate(int FindSection)
{   
}

错误:参数字典包含参数的空条目 方法的不可为空类型“System.Int32”的“FindSection” 'System.Web.Mvc.ActionResult 生成(Int32)'

我知道我可以直接通过 pass 1 但我不想硬编码,因为将来如果我需要通过任何其他东西然后 我必须再次更改代码。

我该怎么做???

【问题讨论】:

  • 尝试在您的操作方法中将单词FindSection 替换为Section,然后再次运行。
  • @HarveySpecter: 我不能改变我的参数,因为我在很多地方都使用过这个方法
  • 您必须更改这两个地方的名称。在控制器中的方法名称或 ajax 调用中。它们必须相同才能被识别。
  • 是的,我可以在可能的 ajax 调用中更改名称。但我不能像这样从 ajax:Section.Upper 传递
  • 尝试在您的 ajax 调用的 data 字段中使用 FindSection 代替 Section。

标签: c# asp.net-mvc asp.net-ajax


【解决方案1】:

你只需要传递你想要的项目的索引。

public ActionResult Generate(Section section)
{   

}

$(function () {
  //...
 $.ajax({
            url: '/Section/Generate',
            data: { section: 1} //the controller will receive Super.Lower
 });
 //..
})

【讨论】:

  • 请不要硬核这个
  • @Lacy Jones 对不起,我不明白。能说清楚一点吗?
  • 我的意思是我不能像这样从 ajax 传递:Section.Upper.passing 像这样从 ajax 给出我在问题中描述的错误
【解决方案2】:

将操作代码更改为:

public ActionResult Generate(Section Section) {  }

在 ASP.NET MVC 中也不要使用硬编码的 url,而是使用 url 助手:

$.ajax({
    url: '@Url.Action("Generate", "Section")',
    data: { 'Section': section }
 });

编辑:如果更改方法参数不是一个选项,则在ajax 方法中使用正确的名称:

$.ajax({
    url: '@Url.Action("Generate", "Section")',
    data: { 'FindSection': section }
 });

【讨论】:

  • 对不起,我无法更改我的方法参数,因为它在多个地方使用,因此更改它需要在多个地方进行更改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 2015-11-22
  • 2020-03-30
  • 1970-01-01
  • 2011-08-15
  • 2021-07-25
相关资源
最近更新 更多