C# ajax—如何从服务器接收html和json数据?
我已经引用了,但它不能解决我的问题 我正在使用MVC5和c。我通常使用此代码从服务器接收数据,数据类型为json 和控制器代码:C# ajax—如何从服务器接收html和json数据?,c#,ajax,json,asp.net-mvc-5,C#,Ajax,Json,Asp.net Mvc 5,我已经引用了,但它不能解决我的问题 我正在使用MVC5和c。我通常使用此代码从服务器接收数据,数据类型为json 和控制器代码: [httppost] public ActionResult MyAction() { try { return Json(new { result = "true", ex = "" }); } catch (Exception e) { return Json(new { result = "false", e
[httppost]
public ActionResult MyAction()
{
try
{
return Json(new { result = "true", ex = "" });
}
catch (Exception e)
{
return Json(new { result = "false", ex = e.Message });
}
}
[httppost]
public ActionResult MyAction()
{
try
{
return PartialView("_MyPartialView");
}
catch (Exception e)
{
return Json(new { result = "false", ex = e.Message });
}
}
对于数据类型为html,我使用这种方式:
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "html",
success: function (data) {
$(".myDiv").append(data);
}
});
控制器应为:
[httppost]
public ActionResult MyAction()
{
return PartialView("_MyPartialView");
}
我的问题是:有没有办法把所有这些结合在一起
事情是这样的:
$.ajax({
url: "/MyController/MyAction",
type: "POST",
dataType: "json" or "html",
success: function (data) {
if (data.result) {
$(".myDiv").append(data);
}
else {
alert(data.ex);
}
}
});
和想象控制器代码:
[httppost]
public ActionResult MyAction()
{
try
{
return Json(new { result = "true", ex = "" });
}
catch (Exception e)
{
return Json(new { result = "false", ex = e.Message });
}
}
[httppost]
public ActionResult MyAction()
{
try
{
return PartialView("_MyPartialView");
}
catch (Exception e)
{
return Json(new { result = "false", ex = e.Message });
}
}
是的,你可以:
@section scripts
{
<script>
$(function() {
$.ajax({
url: "/Home/MyAction",
type: "POST",
success: function (data) {
if (!data.result) {
$(".myDiv").append(data);
}
else {
alert(data.ex);
}
}
});
});
</script>
}
因此,如果数据不包含anonymouse对象,则意味着它包含PartialView返回的HTML。有什么问题?你得到了什么错误?@sirwanafif问题是:如果控制器返回return PartialView\u MyPartialView;,那么什么是data.result?@kevin,data.result==null意味着它给出一个paritalview结果,或者data.result==false意味着它给出json结果,因为actionResult返回所有类型的结果。@Vijay你的意思是:if data.result{}应该是if data.result==null{},不是吗?ifdata.result==null | data.result=={$.myDiv.appenddata;}else{alertdata.ex;}如果结果为null,则表示partialview输出;如果结果为value,则表示json结果。它不再需要数据类型。