Reputation: 48476
this is my partial:
@model RazorSharpBlog.Models.MarkdownTextAreaModel
<div class="wmd-panel">
<div id="[email protected]"></div>
@Html.TextAreaFor(m => m.Name, new { @id = "wmd-input-" + @Model.Name, @class = "wmd-input" })
</div>
<div class="wmd-panel-separator"></div>
<div id="[email protected]" class="wmd-panel wmd-preview"></div>
<div class="wmd-panel-separator"></div>
I'm trying to include it like this in my View
:
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title)
@Html.Partial("MarkdownTextArea", new { Name = "content" })
<input type="submit" value="Post" />
}
these are the model classes:
public class MarkdownTextAreaModel
{
[Required]
public string Name { get; set; }
}
public class BlogContentModel
{
[Required]
[Display(Name = "Post Title")]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Post Content")]
public string Content { get; set; }
}
What am I doing wrong, how should I do this in order to make my partial reusable?
Upvotes: 4
Views: 20349
Reputation: 1038710
Your partial expects an instance of the MarkdownTextAreaModel
class. So do so, instead of passing an anonymous object which would throw anyways:
@Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" })
Now this being said a far better solution would be to adapt your view model, so that it contains a reference to MarkdownTextAreaModel
and use editor templates instead of partials in your views, just like so:
public class BlogContentModel
{
[Required]
[Display(Name = "Post Title")]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[Display(Name = "Post Content")]
public string Content { get; set; }
public MarkdownTextAreaModel MarkDown { get; set; }
}
then of course readapt the controller serving this view so that it populates the MarkDown
of your view model:
public ActionResult Foo()
{
BlogContentModel model = .... fetch this model from somewhere (a repository?)
model.MarkDown = new MarkdownTextAreaModel
{
Name = "contect"
};
return View(model);
}
and then inside your main view simply:
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title)
@Html.EditorFor(x => x.MarkDown)
<input type="submit" value="Post" />
}
and then in order to follow standard conventions move your partial to ~/Views/YourControllerName/EditorTemplates/MarkdownTextAreaModel.cshtml
and now everything will magically come into place as it should.
Upvotes: 14
Reputation: 3956
@using (Html.BeginForm()) {
@Html.LabelFor(m => m.Title) @Html.TextBoxFor(m => m.Title)
@Html.Partial("MarkdownTextArea", new MarkdownTextAreaModel { Name = "content" })
<input type="submit" value="Post" />
}
Upvotes: 0