매개 변수에 따라 JSON 또는 부분 html을 반환하는 컨트롤러 액션을 만들려고 합니다. 결과를 비동기적으로 MVC 페이지에 반환하는 가장 좋은 방법은 무엇인가요?
액션 메서드에서 Json(객체)를 반환하여 페이지에 JSON을 반환합니다.
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
그런 다음 Ajax를 사용하여 액션 메서드를 호출합니다. 다음과 같은 뷰 페이지의 헬퍼 메서드 중 하나를 사용할 수 있습니다.
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
SomeMethod는 반환된 Json 객체를 평가하는 자바스크립트 메서드입니다.
일반 문자열을 반환하려면 ContentResult를 사용하면 됩니다:
public ActionResult SomeActionMethod() {
return Content("hello world!");
}
ContentResult는 기본적으로 콘텐츠 유형으로 텍스트/일반을 반환합니다.
이것은 오버로드가 가능하므로 사용할 수도 있습니다:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
내 생각엔 카스파티페스 요청을 고려해 봐야 합니다. 나는 내 현재 프로젝트를 반품하십시오 유형으로 이를 활용한 정확한 내용은 다음과 같다.
이 같은 작업이 컨트롤러거 테스트할 수 있는 고객의 요청에 따라 객체에는
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"))
{
//
}
그런 다음 뷰의 중시하는 부분 응답 xhtml 의 영문 구현 사례.
Jquery 에 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 getJSON 함수를 사용하는 것입니다. 이 함수는
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
메서드를 호출할 수 있습니다.
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
내가 찾은 구현할 수 있는 몇 가지 문제 때문에 발생하는 두통 JQuery 나 MVC 아약스 통화를 공유함을 솔루션뀉뀉뀉뀉 삽입하십시오.
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);
}
대안 솔루션으로 린코딩 레임워크
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
기본 클래스 및 제슨루슬트 파르시알비에라스울트 상속됩니다 악타이온레술트. 만일 반품하십시오 유형은 너희가운데 방법을 따라 동적으로 출력입니다 악타이온레술트 했다.
public ActionResult DynamicReturnType(string parameter)
{
if (parameter == "JSON")
return Json("<JSON>", JsonRequestBehavior.AllowGet);
else if (parameter == "PartialView")
return PartialView("<ViewName>");
else
return null;
}
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);
}
}
이 방법 () '' 리퀘스트롬이사이아스리퀘스트 매우 단순하다. http 헤더 뿐입니다 검사를 위한 '는' 스믈하트프리퀘스트 의 값을 x 와 요청되었습니다. 헤더입니다 규칙수신되는 요청 여부를 확인하기 위해, 이는 대부분의 브라우저에서 및 ajax 프레임워크와도 자동으로 붙습니다.
사용자 정의 확장명의 여부를 확인할 수 있어 연락할 수 있는 방법을 대한 요청인지 json 방관하겠나 어디서부터든 리퀘스트롬이사이아스리퀘스트 () 이 마찬가지로 확장명은 방법:
using System;
using System.Web;
public static class JsonRequestExtensions
{
public static bool IsJsonRequest(this HttpRequestBase request)
{
return string.Equals(request["format"], "json");
}
}
출처: # _javascript_rendering /ch06.html https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/ 9781449321932