Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to make a non ActionResult Method to return an ActionResult... Or best/neatest workaround?
    primarykey
    data
    text
    <p>I have an object from a database that is used in a lot of places in my application.</p> <p>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.</p> <p>However, it was possible that this object did not exist, and if it did not, my code would create it and return it.</p> <p>For example:</p> <pre><code>public ActionResult Index() { var model = GetTheObject(); return View(model); } public MyComplicatedObject GetTheObject() { MyComplicatedObject passback = ...database query.... if(passback==null) create the object here.... return passback; } </code></pre> <p>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.</p> <p>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.</p> <p>I know the following won't work, but ideally this is what I want:</p> <pre><code>public MyComplicatedObject GetTheObject() { MyComplicatedObject passback = ...database query.... if(passback==null) return View("CreateObject"); return passback; } </code></pre> <p>Obviously though, this will not work.</p> <p>The best solution I can think of is to basically return either null or an exception, then have <code>if(passback==null)</code>&amp;<code>return View("CreateObject");</code> (in case of a null) on the ActionResult.</p> <p>However, as I want to repeat this in a few places, it makes more sense to be able to just have <code>GetTheObject()</code> in one line/call from the ActionResult and nothing else.</p> <p>Is there any way to achieve this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload