Using Ajax.BeginForm with ASP.NET MVC 3 Razor

后端 未结 8 1015
面向向阳花
面向向阳花 2020-11-22 01:23

Is there a tutorial or code example of using Ajax.BeginForm within Asp.net MVC 3 where unobtrusive validation and Ajax exist?

This is an elusive topic f

8条回答
  •  无人及你
    2020-11-22 01:37

    Example

    //In Model

    public class MyModel
    {  
       [Required]
        public string Name{ get; set; }
    }
    

    //In PartailView //PartailView.cshtml

    @model MyModel
    
    
    @Html.LabelFor(model=>model.Name)
    @Html.EditorFor(model=>model.Name) @Html.ValidationMessageFor(model => model.Name)

    In Index.cshtml view

    @model MyModel
    
    @{Html.RenderPartial("PartialView",Model)}
    @using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" })) {
    }

    In Controller

    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();
                }
            }
    

    you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model and append the content in "targetId" div in Index.cshtml. I this way by catching RenderHtml of partial view you can apply validation.

提交回复
热议问题