Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 MVC Rest和返回视图_Asp.net Mvc 3_C# 4.0_Restful Architecture - Fatal编程技术网

Asp.net mvc 3 MVC Rest和返回视图

Asp.net mvc 3 MVC Rest和返回视图,asp.net-mvc-3,c#-4.0,restful-architecture,Asp.net Mvc 3,C# 4.0,Restful Architecture,我试图在我的控制器上实现restful约定,但不确定如何处理失败的模型验证,将其从Create操作发送回“New”视图 public class MyController : Controller { public ActionResult Index() { return View(); } public ActionResult New() { return View(); } [HttpPost]

我试图在我的控制器上实现restful约定,但不确定如何处理失败的模型验证,将其从Create操作发送回“New”视图

public class MyController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult New()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(MyModel model)
    {
        if(!ModelState.IsValid)
        {
             // Want to return view "new" but with existing model
        }

        // Process my model
        return RedirectToAction("Index");
    }
}

当然我不熟悉其他的惯例,所以我可能离这里太远了。。。我找不到一个消息来源说新方法必须在几分钟内通过谷歌搜索无参数

您可以将新方法更改为

public ActionResult New(MyModel model = null)
{
    return View("New", model);
}
然后在你的创作中

    if(!ModelState.IsValid)
    {
         return New(model)
         // Want to return view "new" but with existing model
    }
并在新视图中检查是否设置了模型。新功能在没有参数的情况下仍能正常工作。

简单地说:

[HttpPost]
public ActionResult Create(MyModel model)
{
    if(!ModelState.IsValid)
    {
        return View("New", model);
    }

    // Process my model
    return RedirectToAction("Index");
}

-1,这将调用新操作,更不用说它将不会像您在创建操作的上下文中那样工作,该操作将查找Create.cshtml视图。这不正是他想要的吗?不,这不是他想要的。他希望从Create操作中呈现新视图,而不是调用新操作。这是有区别的。看,我知道。我只是不太喜欢从不同的行动中返回不同的观点。视图所需的操作中可能存在逻辑,否则可能会被忽略。我更喜欢通过调用New但是使用一个模型来处理这种情况,然后在逻辑中检查模型是否为null。这是一种错误的模式。通常在GET操作中,您有从DB获取模型的代码,而在POST操作中,此模型作为用户输入来自默认的模型绑定器。如果通过返回GET操作来调用它,则会丢失用户在表单中输入的内容。正如我所说,您的代码将无法工作,因为它找不到Create.cshtml视图。在新操作中,必须返回ViewNew,model;。