2016-03-16 58 views
2

。我無法返回視圖()。請檢查下面的代碼。 這是Action。當我使用Request.IsAjaxRequest()時Request.IsAjaxRequest不會喚醒mvc

public ActionResult Index() 
    { 
     if (!Request.IsAjaxRequest()) { 
      return View("ajexview");    
     } 
     return view("About"); 
    } 

這個觀點

<script> 
$(function() { 
    $("button").click(function() { 
     var car = { Make: 'Audi', Model: 'A4 Avant', Color: 'Black', Registered: 2013 }; 
     $.ajax({ 
      type: "POST", 
      url: "/home/index/", 
      data: car, 
      datatype: "html", 
      success: function (data) { 
       $('#result').html(data); 
      } 
     }); 
    }); 
}); 

<button>Click me</button> 

當我張貼有關視圖無法返回

+0

您應該在控制器中使用其他操作來處理Ajax請求。通常,當你發出一個Ajax請求時,你將它指向一個返回類似'JsonResult'的動作。看看這個問題的控制器代碼:http://stackoverflow.com/questions/16186083/making-a-simple-ajax-call-to-controller-in-asp-net-mvc –

回答

0

首先,我不知道,如果你的指數行動將會被你的ajax呼叫所擊中。你正在做一個反對獲得行動的帖子。爲了得到Request.IsAjaxRequest()按預期方式工作,無論是嘗試再創建一個控制器動作,並與HttpPost將其標記屬性像這樣,

[HttpPost] 
public ActionResult Index(Car car) 
{ 
    if (!Request.IsAjaxRequest()) { 
     return PartialView("ajexview");    
    } 
    return View("About"); 
} 

還要注意的是,在if (!Request.IsAjaxRequest())塊我就要回「 ajexview「作爲PartialView

,或者如果你的目的是要打擊的get索引操作,那麼你需要做一個ajax「得到」的請求,而不是像

$.ajax({ 
     type: "GET", 
     url: "/home/index/", 
     success: function (data) { 
     $('#result').html(data); 
    } 
}); 
0

確保在正確的地方和秩序,以渲染腳本您的_layout.cshtml:

eg頂部: ...

<title>@ViewBag.Title</title> 
    @Styles.Render("~/Content/css") 
    @Scripts.Render("~/bundles/modernizr") 
</head> 

...和底部:

  @Scripts.Render("~/bundles/jquery") 
     @Scripts.Render("~/bundles/jqueryval") 
     @Scripts.Render("~/bundles/bootstrap") 
     @Styles.Render("~/Content/datatables") 
     @Scripts.Render("~/bundles/datatables") 
     <!-- etc. --> 
     @RenderSection("scripts", required: false) 
    </body> 
</html> 

另外要注意自己BundleConfig.cs的建設。

相關問題