The MVC extension controller converts some views into strings (with verification information) and transmits them to the front-end view in json format.

Source: Internet
Author: User

When we use jQuery to asynchronously submit form data, we need to convert some views into strings (with verification information) and pass them to the front-end view in json format.

 

Use jQuery to asynchronously load some views and append the returned content to a div on the page:

Using System. ComponentModel. DataAnnotations;

 
namespace MvcApplication1.Models
{
    public class Pet
    {
        public int Id { get; set; }
 
[Display (Name = "Pet")]
[Required (ErrorMessage = "Required")]
        public string Name { get; set; }
    }
}
 

Extends the Controller to convert part of the View content into strings.

using System.IO;
 
namespace System.Web.Mvc
{
    public static class ControllerExtensions
    {
// Convert part of the View content to a string based on some view names
        public static string RenderPartialViewToString(this Controller controller, string partialViewName)
        {
            return controller.RenderPartialViewToString(partialViewName, null);
        }
 
// Convert part of the View content to a string based on some view names and models.
        public static string RenderPartialViewToString(this Controller controller, string partialViewName, object model)
        {
// If partialViewName is empty, the action name is used as the part view name.
            if (string.IsNullOrEmpty(partialViewName))
            {
                partialViewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }
 
// Place the model in the Controller. ViewData. Model attribute.
            controller.ViewData.Model = model;
 
            using (var sw = new StringWriter())
            {
// Use the view engine to obtain the ViewEngineResult type based on some view names in the current ControllerContext.
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName);
 
// Create ViewContext
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData,
                    controller.TempData, sw);
 
// Write the content to StringWriter
                viewResult.View.Render(viewContext, sw);
 
                //StringWriter→string
                return sw.GetStringBuilder().ToString();
            }
        }
    }
}
 

Home/Index. cshtml view. Before submission, request the html content of some views in asynchronous Get mode. Click Submit to request some view string content returned from the Controller in asynchronous Post mode.

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<div id="petContent">
</div>
<div>
<Input type = "button" id = "btn" value = "Submit"/>
</div>
 
@section scripts
{
    <script type="text/javascript">
        $(function() {
            init();
 
// Submit
            $('#btn').click(function() {
                $.ajax({
                    cache: false,
                    url: '@Url.Action("SaveData", "Home")',
                    type: "POST",
                    data: $('#addForm').serialize(),
                    success: function (data) {
                        $('#petContent').empty();
                        $('#petContent').append(data.message);
                    },
                    error: function (jqXhr, textStatus, errorThrown) {
Alert ("error occurred '" + jqXhr. status + "' (status: '" + textStatus + "', error: '" + errorThrown + "')");
                    }
                 });
            });
        });
 
        function init() {
            $.ajax({
                cache: false,
                url: '@Url.Action("GetPet", "Home")',
                contentType: 'application/html;charset=utf-8',
                type: "GET",
                success: function(result) {
                    $('#petContent').append(result);
                },
                error: function(xhr, status) {
Alert ("failed to load content" + status );
                }
            });
        }
    </script>
}
 

 

HomeController part:

using System.Web.Mvc;
using MvcApplication1.Models;
 
namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
// Home Page
        public ActionResult Index()
        {
            return View();
        }
 
// Receives asynchronous Get requests. Some views are returned to the front-end view in html.
        public ActionResult GetPet()
        {
            return PartialView();
        }
 
// Receives asynchronous Post requests. Some views are converted to strings and returned to the front-end view in json format.
        [HttpPost]
        public ActionResult SaveData(Pet pet)
        {
            if (ModelState.IsValid)
            {
                //TODO: insert into database
                return Json(new {msg = true, message = this.RenderPartialViewToString("Success", pet)});
            }
            return Json(new { msg = false, message = this.RenderPartialViewToString("GetPet", pet) });
        }
    }
}
 

 

Home/GetPet. cshtml partial view:

@model MvcApplication1.Models.Pet
 
@using (Html.BeginForm("SaveData", "Home", FormMethod.Post, new {id = "addForm"}))
{
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
}

 

Home/Success. cshtml partial view:

@model MvcApplication1.Models.Pet
 
@ Model. Name submitted successfully!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.