ASP.Net MVC, dynamic property and editor for / LabelFor

I am using MVC 3 w / Razor and using the new dynamic ViewBag property. I would like to use the ViewBag property with the EditorFor / LabelFor Html helpers, but cannot understand the syntax.

There is an @model set in the view, but the object I'm trying to use is not part of this model. I know I can create a ViewModel, but that is not what I want.

Can anyone help?

Controller:

   var myModel= _repo.GetModel(id);
   var newComment = new Comment();

   ViewBag.NewComment = newComment;

   return View(myModel);

View:

@model Models.MyModel

@(Html.EditorFor(ViewBag.NewComment.Comment))
+3
source share
3 answers

I have not tried, but this should work, I think.

@(EditorFor(m => ViewBag.NewComment)

You can use Linq-to-SQL syntax, but use a completely different object on the right side.

+5
source

, , :

@Html.EditorFor(ViewBag.NewComment)

, ViewBag , NewComment, , .

@Html.EditorFor(ViewBag.NewComment as Comment)

Update

, EditorFor . , EditorFor EditorForModel , ViewModel. , , ViewBag?

+1

- ViewData , , Html.DisplayFor().

views ViewData

var newCommentModel = ( NewComment )ViewBag.NewComment;

,

@Html.DisplayFor( model => newCommentModel )

The expression tree now contains a strongly typed model, and the DisplayTemplate is displayed correctly.

+1
source

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


All Articles