How to assign Model in controller to send back to View

Nawaz Ali asked on July 15, 2021 18:07

Hi, kind of a basic question.

I have a view that works fine

@addTagHelper *, Kentico.Content.Web.Mvc
@model Kentico.Content.Web.Mvc.Routing.IPageViewModel<CMS.DocumentEngine.Types.MCI.Standard>
@{
    ViewBag.Title = Model.Page.DocumentName;
}

I have a controller currently empty

namespace NewSite.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

The Model is just a kentico generated one with a few text fields.

When I call the view '/Home' it works fine but when I call the controller '/Home/Index' I get the 'Object reference not set to an instance of an object' error.

How do I assign the model in the controller to send back to the view?

Correct Answer

Sean Wright answered on August 14, 2021 20:04

Nawaz,

You are confusing 2 ways of using Kentico Xperience's routing.

You can't use both a Controller + View model and IPageViewModel. IPageViewModel is used by Kentico Xperience when _it handles the controller and view model_.

If you want to use IPageViewModel then you need to use Basic Routing which means you don't have a Controller.

If you want to create a custom View Model class, then you need a Controller and you need to set up Advanced Routing.

0 votesVote for this answer Unmark Correct answer

Recent Answers


Brenden Kehren answered on July 15, 2021 18:25

These are basics of MVC5. You may wanna take a look at the at some documentation around that.

To give you a bit more specific with your issue. With your controller, if you have it named HomeController with an ActionResult of Index, by default, the controller will look for the view named Index in the /Views/Home folder. The /Views/Home folder and the Index view in that folder is "automatically" hooked up because your controller name is Home. So by default it's looking for that Home folder in the Views folder and displaying the ActionResults name as a view name.

0 votesVote for this answer Mark as a Correct answer

Nawaz Ali answered on July 15, 2021 21:11 (last edited on July 15, 2021 21:43)

Thanks Brenden, Yeh I know it's kind of basic but I just can't figure the model declaration syntax out in the controller. The model has to be of IPageViewModel<CMS.DocumentEngine.Types.MCI.Standard>.

The url '/Home/Index' works ok if I remove the 'Model.Page.xxx' references from the view. So the routing is fine it's just passing the model back to the view bit. Is there any example code you could show me?

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.