programing

JSON 또는 부분 html을 반환하는 ASP.NET MVC 컨트롤러 액션

i4 2023. 4. 6. 20:46
반응형

JSON 또는 부분 html을 반환하는 ASP.NET MVC 컨트롤러 액션

파라미터에 따라 JSON 또는 부분 html 중 하나를 반환하는 컨트롤러 액션을 작성하려고 합니다.결과를 비동기적으로 MVC 페이지로 되돌리는 가장 좋은 방법은 무엇입니까?

액션 메서드에서 Json(개체)을 반환하여 JSON을 페이지로 되돌립니다.

public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}

그럼 Ajax를 사용하여 액션 메서드를 호출해 주세요.ViewPage에서 다음과 같은 도우미 메서드 중 하나를 사용할 수 있습니다.

<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>

Some Method는 jascript 메서드로 반환된 Json 객체를 평가합니다.

일반 문자열을 반환하려면 ContentResult를 사용합니다.

public ActionResult SomeActionMethod() {
    return Content("hello world!");
}

"Content Result" / "Content" 콘텐츠라고 입력합니다.
이는 과부하가 되기 때문에 다음 작업도 수행할 수 있습니다.

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");

요청의 Accept Types를 검토해야 할 것 같습니다.현재 진행 중인 프로젝트에서 다음과 같이 올바른 콘텐츠 유형을 반환하기 위해 사용하고 있습니다.

컨트롤러에 대한 작업은 요청 개체와 동일하게 테스트할 수 있습니다.

if (Request.AcceptTypes.Contains("text/html")) {
   return View();
}
else if (Request.AcceptTypes.Contains("application/json"))
{
   return Json( new { id=1, value="new" } );
}
else if (Request.AcceptTypes.Contains("application/xml") || 
         Request.AcceptTypes.Contains("text/xml"))
{
   //
}

그런 다음 보기의 aspx를 구현하여 부분 xhtml 응답 사례를 충족할 수 있습니다.

그런 다음 jQuery에서 type 파라미터를 json으로 전달하여 가져올 수 있습니다.

$.get(url, null, function(data, textStatus) {
        console.log('got %o with status %s', data, textStatus);
        }, "json"); // or xml, html, script, json, jsonp or text

JSON 데이터를 처리하는 또 다른 좋은 방법은 JQuery getJ를 사용하는 것입니다.SON 기능에 전화할 수 있습니다.

public ActionResult SomeActionMethod(int id) 
{ 
    return Json(new {foo="bar", baz="Blech"});
}

jquery getJ로부터의 메서드단순하게 SON 메서드...

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);

JQuery와의 MVC AJAX GET 콜 구현에서 몇 가지 문제가 발견되어 두통을 일으켰습니다.여기서 솔루션을 공유하겠습니다.

  1. ajax 콜에는 반드시 데이터 타입 'json'을 포함합니다.그러면 반환된 JSON 개체가 자동으로 해석됩니다(서버가 유효한 json을 반환하는 경우).
  2. 를함 include include include JsonRequestBehavior.AllowGet; 이 500되었습니다(MVC는 HTTP 500 에러를 됩니다).dataType: json(어느 쪽인가 하면)
  3. cache: false콜에 최종적으로 304 대신)을 수 는 요청을 처리하지 않습니다.$ajax는 200을 사용하여HTTP 304를 합니다.
  4. 마지막으로 json은 대소문자를 구분하기 때문에 요소의 대소문자가 서버측과 클라이언트측에서 일치해야 합니다.

JQuery 샘플:

$.ajax({
  type: 'get',
  dataType: 'json',
  cache: false,
  url: '/MyController/MyMethod',
  data: { keyid: 1, newval: 10 },
  success: function (response, textStatus, jqXHR) {
    alert(parseInt(response.oldval) + ' changed to ' + newval);                                    
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert('Error - ' + errorThrown);
  }
});

MVC 코드 예시:

[HttpGet]
public ActionResult MyMethod(int keyid, int newval)
{
  var oldval = 0;

  using (var db = new MyContext())
  {
    var dbRecord = db.MyTable.Where(t => t.keyid == keyid).FirstOrDefault();

    if (dbRecord != null)
    {
      oldval = dbRecord.TheValue;
      dbRecord.TheValue = newval;
      db.SaveChanges();
    }
  }

    return Json(new { success = true, oldval = oldval},
                JsonRequestBehavior.AllowGet);
}

질문의 나머지 절반에 대한 답변은 다음과 같습니다.

return PartialView("viewname");

URL 파트/파라미터에 따라 요청이 JSON 또는 HTML 중 어느 것을 원하는지 결정하는 방법을 찾아야 합니다.

인코딩 프레임워크 대체 솔루션

동작 반환 json

컨트롤러

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncJson(new SomeVm(){Id = 1,Name ="Inc"});
    }

레이저 페이지

@using (var template = Html.Incoding().ScriptTemplate<SomeVm>("tmplId"))
{
    using (var each = template.ForEach())
    {
        <span> Id: @each.For(r=>r.Id) Name: @each.For(r=>r.Name)</span>
    }
}

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core()
                              .Insert
                              .WithTemplate(Selector.Jquery.Id("tmplId"))
                              .Html())
  .AsHtmlAttributes()
  .ToDiv())

동작 반환 html

컨트롤러

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncView();
    }

레이저 페이지

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core().Insert.Html())
  .AsHtmlAttributes()
  .ToDiv())

당신은 이것을 아주 잘 다루고 있는 이 매우 유용한 기사를 보는 것이 좋을지도 모릅니다!

이 문제에 대한 좋은 해결책을 찾는 사람들에게 도움이 될 것 같아서요.

http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx

PartialViewResult 및 JSONReuslt는 기본 클래스 ActionResult에서 상속됩니다.따라서 반환 유형이 결정되면 메서드 출력을 ActionResult로 동적으로 선언합니다.

public ActionResult DynamicReturnType(string parameter)
        {
            if (parameter == "JSON")
                return Json("<JSON>", JsonRequestBehavior.AllowGet);
            else if (parameter == "PartialView")
                return PartialView("<ViewName>");
            else
                return null;


        }

MVC3로 업그레이드 되신 분들을 위해 MVC3와 Json을 사용하는 깔끔한 방법이 여기 있습니다.

    public ActionResult GetExcelColumn()
    {            
            List<string> lstAppendColumn = new List<string>();
            lstAppendColumn.Add("First");
            lstAppendColumn.Add("Second");
            lstAppendColumn.Add("Third");
  return Json(new { lstAppendColumn = lstAppendColumn,  Status = "Success" }, JsonRequestBehavior.AllowGet);
            }
        }

요청에 따라 다양한 출력을 생성하는 유연한 접근 방식

public class AuctionsController : Controller
{
  public ActionResult Auction(long id)
  {
    var db = new DataContext();
    var auction = db.Auctions.Find(id);

    // Respond to AJAX requests
    if (Request.IsAjaxRequest())
      return PartialView("Auction", auction);

    // Respond to JSON requests
    if (Request.IsJsonRequest())
      return Json(auction);

    // Default to a "normal" view with layout
    return View("Auction", auction);
  }
}

Request.IsAjaxRequest()방법은 매우 간단합니다.X-Requested-With 헤더의 값이 다음 값인지 확인하기 위해 HTTP 헤더의 착신 요구를 체크할 뿐입니다.XMLHttpRequest대부분의 브라우저와 AJAX 프레임워크에 의해 자동으로 추가됩니다.

요청과 같이 어디서든 호출할 수 있도록 요청이 json에 대한 것인지 여부를 확인하는 커스텀 확장 메서드입니다.IsAjaxRequest() 확장 메서드:

using System;
using System.Web;

public static class JsonRequestExtensions
{
  public static bool IsJsonRequest(this HttpRequestBase request)
  {
    return string.Equals(request["format"], "json");
  }
}

출처 : https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering

언급URL : https://stackoverflow.com/questions/227624/asp-net-mvc-controller-actions-that-return-json-or-partial-html

반응형