.net 是否可能有一个MVC控制器具有两个同名动作,参数为T和List

.net 是否可能有一个MVC控制器具有两个同名动作,参数为T和List,.net,asp.net-mvc-3,.net,Asp.net Mvc 3,我想在我的控制器上有两个同名的方法,但唯一的区别是参数一个取T,另一个取List [HttpPost] public ActionResult Edit(myType parameter) { //snip } [HttpPost] public ActionResult Edit(List<myType> parameter) { //snip } 这里的关键是,您当然可以使用重载来获取一个列表,即使只传递一个对象,您也只会得到一个包含1项的列表。您所需要做

我想在我的控制器上有两个同名的方法,但唯一的区别是参数一个取T,另一个取List

[HttpPost]
public ActionResult Edit(myType parameter)
{ 
    //snip
}

[HttpPost]
public ActionResult Edit(List<myType> parameter)
{ 
    //snip
}

这里的关键是,您当然可以使用重载来获取一个列表,即使只传递一个对象,您也只会得到一个包含1项的列表。您所需要做的就是将数据作为json数组传入。

这似乎是不可能的,框架会对您真正想要调用的操作感到困惑。但是,您可以简单地维护上述操作之一吗?或者每个人做不同的事情?如果是这样,那么您的url方案可能需要稍作修改

如果这两个参数的作用大致相同,则如果希望模式1的单个值或模式2的更多值,则可以向specy添加一个参数:

[HttpPost]
public ActionResult Edit(List<myType> parameter, bool? multiple)
{ 
    var multipleValues = multiple.GetValueOrDefault(true);
    if (!multipleValues)  ....
}
编辑

您可以使用自定义ModelBinder来反序列化json数据

活页夹:

public class MyTypeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;

        // reset input stream
        request.InputStream.Position = 0;

        // read content
        var jsonString = request.ContentEncoding.GetString(request.BinaryRead((int)request.InputStream.Length));

        var serializer = new JavaScriptSerializer();

        return jsonString.TrimStart().StartsWith("[")
            // array, just parse it
            ? serializer.Deserialize<List<MyType>>(jsonString)
            // single object, add to a list
            : new List<MyType>() { serializer.Deserialize<MyType>(jsonString) };
    }
}
然后,关于行动:

public ActionResult Test([ModelBinder(typeof(MyTypeBinder))] List<MyType> type) 
{
   ....
}
内森

你可以试试这个:

[HttpPost, ActionName("Edit")]
public ActionResult EditMytype(myType parameter)
{ 
    //snip
}

[HttpPost]
public ActionResult Edit(List<myType> parameter)
{ 
    //snip
}

在一个项目中得到了一些类似的东西

注意,这里的问题类似,但不同:不幸的是,这引发了与上面相同的异常。dang,这在我使用它的场景中确实有效。json.stringify定义正确吗??i、 e.您是否尝试过使用不同的控制器操作名称进行测试以确保其正常工作?我已经测试了注释一个定义,然后它正常工作。不幸的是,这不会成功,因为ajax调用发送一个数组或单个对象,如果它始终是一个数组,那么就可以了,但如果是单个对象,则参数将为null。
[HttpPost, ActionName("EditType1")]
public ActionResult Edit(myType parameter)
{ 
    //snip
}

[HttpPost, ActionName("EditType2")]
public ActionResult Edit(List<myType> parameter)
{ 
    //snip
}
[HttpPost, ActionName("EditType1")]
public ActionResult Edit(myType parameter)
{ 
    //snip
}

[HttpPost, ActionName("EditType2")]
public ActionResult Edit(List<myType> parameter)
{ 
    //snip
}
/controllername/edittype1

/controllername/edittype2