dalam HTML

@section Scripts
{
<script type="text/javascript">

    $(document).ready(function() {

        $('#bSubmit').click(function(event) {
            event.preventDefault();

            var formData = new FormData();
            formData.append('@Html.Get__RequestVerificationTokenString()', '@Html.GetAntiForgeryToken()');
            formData.append('request.MessageId', @Model.MessageId);
            formData.append('request.Message', $('#Message').val());

            var xmlHttpRequest = new XMLHttpRequest();
            if (!window.XMLHttpRequest) {
                xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlHttpRequest.open("POST",
                '@Url.Action("Send", "Page", new {area = "Question"})',
                true);

            xmlHttpRequest.onloadend = function() {
                var response = JSON.parse(xmlHttpRequest.responseText);

                $('#prButton').removeClass("visible");
                $('#prButton').addClass("invisible");

                switch (response.Type) {
                case 10:
                    LOG(response.PartialView);

                    $('#layoutSingleMessageItems .card-box').replaceWith(response.PartialView);
                    break;
                case -13:
                    @Html.ShowAlert("خطا در ارسال اطلاعات!");
                    break;
                }
            };

            xmlHttpRequest.send(formData);

        });

    });

</script>
}
<div class="row">

    <div class="col-md-7">
        @Html.Partial("Par_SingleMessageItem", Model.SingleMessageItems)
    </div>

<div class="col-md-5">
    <div class="card-box">
        <form>
            @Html.AntiForgeryToken()
            <div class="form-group col-md-12">
                <label class="col-form-label">پاسخ</label>
                <textarea rows="8" id="Message" placeholder="لطفا پاسخ خود را وارد کنید ..."></textarea>

            </div>

            <div class="form-group col-md-12 m-t-10">

                <button id="bSubmit" type="submit">
                    ارسال پاسخ

                </button>
            </div>

        </form>

    </div>
</div>

di PartialView (Par_SingleMessageItem)

@model List<_4Wheels.Areas.Question.Models.SingleMessage.SingleMessageItem>

<div id="layoutSingleMessageItems" class="card-box">
    <div class="card-box">
        @{
            foreach (var item in Model)
            { 
                //code
            }
         }
   </div>
</div>

di Pengontrol

[HttpPost]
public ActionResult Send() {
   /*
      items = list object
   */

   return Json(new SendAnswerResponse {
       Type = 10,
       SingleMessageItems = PartialView("Par_SingleMessageItem" , items)
   });
}

di SendAnswerResponse

public class SendAnswerResponse : MvcResponse
{
    public PartialViewResult SingleMessageItems { get; set; }
}

Semua kode ini berfungsi dengan baik tetapi $('#layoutSingleMessageItems .card-box'). replaceWith(response.PartialView); Tidak berfungsi, tidak membuat kesalahan Mengembalikan PartialView yang diinginkan hanya tag tidak diperbarui.

Saya bahkan memasukkannya ke Console.log (response.PartialView) untuk menampilkan pesan ini

Model: (5) […] ​​ 0: Objek { Pesan: "fdgdfgdfg", Nama pengguna: "", MessageDate: "1398-08-06 23:01:11", … } ​​ 1: Objek { Pesan: "dsafd", Nama Pengguna: "", MessageDate: "1398-08-07 08:34:19", … } ​​ 2: Objek { Pesan: "vcgdsafd", Nama pengguna: "", MessageDate: "1398-08-07 08:34:58", … } ​​ 3: Objek { Pesan: "fdgfdg", Nama Pengguna: "", MessageDate: "1398-08-07 08:42:43", … } ​​ 4: Objek { Pesan: "fdgfdg", Nama pengguna: "", MessageDate: "1398-08-07 08:42:54", … } ​​ panjang: 5 ​​ : Himpunan [] kami TempData: Larik [] kami Lihat: null kami ViewBag: Objek {} kami LihatData: [] ​​ panjang: 0 ​​ : Himpunan [] kami ViewEngineCollection: Array [ {…} ] kami ViewName: "Par_SingleMessageItem" kami : {…} ​​ defineGetter: fungsi defineGetter() ​​ defineSetter: fungsi defineSetter() ​​ lookupGetter: fungsi lookupGetter() ​​ lookupSetter: fungsi lookupSetter() ​​ proto: ​​ konstruktor: fungsi Objek() ​​ hasOwnProperty: fungsi hasOwnProperty() ​​ isPrototypeOf: fungsi isPrototypeOf() ​​ propertyIsEnumerable: fungsi propertyIsEnumerable() ​​ toLocaleString: fungsi toLocaleString() ​​ toSource: fungsi toSource() ​​ toString: fungsi toString() ​​ nilaiDari: fungsi nilaiDari() ​​ : fungsi proto() ​​ : fungsi proto() Utilitas.js:13:13

0
user11657764 29 Oktober 2019, 00:07

2 jawaban

Jawaban Terbaik

Diperbarui dengan kode PartialView berikut

public static string RenderPartialViewToString(ControllerContext context, string viewPath, object model = null, bool partial = false)
        {
            // first find the ViewEngine for this view
            ViewEngineResult viewEngineResult = null;
            if (partial)
                viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
        else
            viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);

        if (viewEngineResult == null)
            throw new FileNotFoundException("View cannot be found.");

        // get the view and attach the model to view data
        var view = viewEngineResult.View;
        context.Controller.ViewData.Model = model;

        string result = null;

        using (var sw = new StringWriter())
        {
            var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
            view.Render(ctx, sw);
            result = sw.ToString();
        }

        return result;
    }

    public static T CreateController<T>(RouteData routeData = null) where T : Controller, new()
    {
        // create a disconnected controller instance
        T controller = new T();

        // get context wrapper from HttpContext if available
        HttpContextBase wrapper;
        if (System.Web.HttpContext.Current != null)
            wrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
        else
            throw new InvalidOperationException("Cannot create Controller Context if no active HttpContext instance is available.");

        if (routeData == null)
            routeData = new RouteData();

        // add the controller routing if not existing
        if (!routeData.Values.ContainsKey("controller") &&
            !routeData.Values.ContainsKey("Controller"))
            routeData.Values.Add("controller", controller.GetType().Name.ToLower().Replace("controller", ""));

        controller.ControllerContext = new ControllerContext(wrapper, routeData, controller);
        return controller;
    }

Dan untuk Digunakan

return Json(new SendAnswerResponse {
   Type = 10,
   SingleMessageItems = MvcHelper.RenderPartialViewToString(
                    MvcHelper.CreateController<Controller Name>().ControllerContext ,
                    "view Path", items , true)
});

https://stackoverflow.com/a/42559538/11657764

0
Mohammad 29 Oktober 2019, 06:20

Apa yang dikembalikan response.SingleMessageItems ? Ini mengembalikan html? atau struktur data? Saya pikir Anda mencoba sesuatu seperti ini

for(var i =0; i< response.SingleMessageItems.length; i++)
{
  $('#layoutSingleMessageItems .card-box').append(response.SingleMessageItems[i]);
}
0
Joshi 28 Oktober 2019, 21:32