Contoh
// Dalam Model
public class MyModel
{
[Required]
public string Name{ get; set; }
}
// Di PartailView //PartailView.cshtml
@model MyModel
<div>
<div>
@Html.LabelFor(model=>model.Name)
</div>
<div>
@Html.EditorFor(model=>model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
Dalam tampilan Index.cshtml
@model MyModel
<div id="targetId">
@{Html.RenderPartial("PartialView",Model)}
</div>
@using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" }))
{
<div>
<input type="submit" value="Add Unit" />
</div>
}
Di Kontroler
public ActionResult Index()
{
return View(new MyModel());
}
public string AddName(MyModel model)
{
string HtmlString = RenderPartialViewToString("PartailView",model);
return HtmlString;
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
Anda harus melewati ViewName dan Model ke metode RenderPartialViewToString. itu akan mengembalikan tampilan Anda dengan validasi yang Anda terapkan dalam model dan menambahkan konten di div "targetId" di Index.cshtml. Saya dengan cara ini dengan menangkap RenderHtml dari tampilan parsial Anda dapat menerapkan validasi.