MVC Rest and returning views

[亡魂溺海] 提交于 2019-12-11 07:59:26

问题


I'm trying to implement the restful convention on my controllers but am not sure how to handle failing model validation in sending it back to the 'New' view from the Create action.

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");
    }
}

回答1:


Simply:

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

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



回答2:


Granted I'm not familiar with the REST conventions, so I may be way off here ... (and I couldn't find a source that said that the New() method has to be parameterless in a few minutes googling)

You could change your New() method to

public ActionResult New(MyModel model = null)
{
    return View("New", model);
}

And then in your Create()

    if(!ModelState.IsValid)
    {
         return New(model)
         // Want to return view "new" but with existing model
    }

And check in your New view if a Model is set or not. The New() will still work perfectly without a parameter as it used to.



来源:https://stackoverflow.com/questions/6723531/mvc-rest-and-returning-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!