开发者

ASP.Net MVC, Dynamic Property and EditorFor/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 can't figure out the syntax.

The View does have a @model set, but the object I am trying to use is not part of that model. I am aware I can create a ViewModel but that is not what I am after.

Can anyone help?

Controller:

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

   ViewBag.NewComment = newComment;

   return View(myModel);

View:

@model Models.MyModel

@(Html.Edi开发者_开发技巧torFor(ViewBag.NewComment.Comment))


I haven't tried it, but this should work I think.

@(EditorFor(m => ViewBag.NewComment)

It is possible to use a Linq-to-SQL syntax, but use a completely different object on the right side.


Not knowing what your Comment Model looks like, my gut reaction would be to just do:

@Html.EditorFor(ViewBag.NewComment)

However, because ViewBag is dynamic, you may need to cast NewComment before you use it, in order to get the EditorFor magic.

@Html.EditorFor(ViewBag.NewComment as Comment)

Update

Strike that, EditorFor can only accept an Expression as a parameter, and that Expression must return a property of the page model. I don't think EditorFor or EditorForModel are going to be of any use to you if you don't want to use a ViewModel. Have you considered switching the roles of whatever it is you're using the Model for, with that of the ViewBag?


If for some reason I need to use ViewData to pass the model into my view I do the following to allow for the Html.DisplayFor() helpers.

In the views code block I cast the ViewData model object to its underlying type

var newCommentModel = ( NewComment )ViewBag.NewComment;

Then I assign the following expression to the helper using the strong-typed reference

@Html.DisplayFor( model => newCommentModel )

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜