Razor element <MyObject element> was not closed

I have a cshtml template and I use Razor to populate it. I am passing an object that has several sub-lists, and I need to get the values ​​from one of the elements in one of the subscriptions for use in the text. So, in the opening tag, I have the following:

@{ 
   var myId = @Model.myId;
   List<MyObject> newObj = @Model.MyList.Where(l => l.Id == myId).ToList();
 }

But when I try to execute the template, it gives an error message that '<' MyObject '>' was not closed, that all elements should have a corresponding self-closing tag or end tag. I understand that this seems to read this as an html tag, but why, since its explicitly inside the programming markup? Can't I call a list object in a razor? If so, how do I get to this particular sub-list of items?

I checked the rest of the page, and html has all its closing marks.

+4
source share
1 answer

I think that to fix the code you will need to do the following:

@{ 
   var myId = Model.myId;
   List<MyObject> newObj = Model.MyList.Where(l => l.Id == myId).ToList();
 }

Which just removes @ in front of the model.

However, I believe that the best solution to your problem is to try to save the logic code in your controller, and not your opinion.

As an example, if you use Partial View.

In your view, you can trigger an action and pass your model as follows:

@Html.Action("MyAction", Model)

This will trigger a controller action that will make your choice ie

[ChildActionOnly]
public ActionResult MyAction(MyModel model)
{
     var newList = model.MyList.Where(l => l.Id == myId).ToList();
     return PartialView("_MyPartial", newList);
}

Then use the attribute @modelin partial ie

@model List<MyObject>
+2
source

Source: https://habr.com/ru/post/1531033/


All Articles