开发者

Is it possible to make a non ActionResult Method to return an ActionResult... Or best/neatest workaround?

开发者 https://www.devze.com 2023-04-11 22:15 出处:网络
I have an object from a database that is used in a lot of places in my application. The actual precise object is a bit complicated to build, and, especially during development, I have changed it seve

I have an object from a database that is used in a lot of places in my application.

The actual precise object is a bit complicated to build, and, especially during development, I have changed it several times. For this reason, I extracted the method out of the Controller and built a method that has a return type of the object.

However, it was possible that this object did not exist, and if it did not, my code would create it and return it.

For example:

public ActionResult Index()
{    
    var model = GetTheObject();
    return View(model);
}

public MyComplicatedObject GetTheObject()
{
    MyComplicatedObject passback = ...database query....

    if(passback==null)
    create t开发者_C百科he object here....

    return passback;
}

However, I no longer want to create a default object. If it does not exist, I want the user to be sent to a view to create a new one.

I don't know if it is because I am coding at almost 4AM, or if I am just not that good, but, a neat way of doing this is escaping me.

I know the following won't work, but ideally this is what I want:

public MyComplicatedObject GetTheObject()
{
    MyComplicatedObject passback = ...database query....

    if(passback==null)
    return View("CreateObject");

    return passback;
}

Obviously though, this will not work.

The best solution I can think of is to basically return either null or an exception, then have if(passback==null)&return View("CreateObject"); (in case of a null) on the ActionResult.

However, as I want to repeat this in a few places, it makes more sense to be able to just have GetTheObject() in one line/call from the ActionResult and nothing else.

Is there any way to achieve this?


I have a similar scenario where I want to return a "NotFound" view in case that my repository returns a null object. I implemented a ViewForModel helper method to avoid repeating myself:

public ActionResult Details(int id)
{
    var model = _repository.Retrieve(id);

    return ViewForModel("Details", model);
}

public ActionResult Edit(int id)
{
    var model = _repository.Retrieve(id);

    return ViewForModel("Edit", model);
}

private ActionResult ViewForModel(string viewName, object model)
{
    return model == null
        ? View("NotFound")
        : View(viewName);
}


Just return null from your method, and have your action method return the create view when it gets a null.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号