2016-09-24 71 views
-1

我想從URL中的ID在ASP.NET MVC控制器,並將其插入PROJECT_ID,波紋管是我的代碼,我嘗試,但它現在爲我工作。如何從URL獲得ID在asp.net MVC控制器

http://localhost:20487/ProjectComponent/Index/1

我的控制器

[HttpPost] 
public JsonResult SaveComponent(OrderVM O, int id) 
{   
    bool status = false; 
    if (ModelState.IsValid) 
    { 
     using (Entities db = new Entities()) 
     { 
      ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description }; 
      foreach (var i in O.ProjComponentActivities) 
      { 
       ProjComponent.ProjComponentActivity.Add(i); 
      } 
      db.ProjComponents.Add(ProjComponent); 
      db.SaveChanges(); 
      status = true; 
     } 
    } 
} 
+1

你的方法是POST,而不是GET(您無法瀏覽到一個POST方法)。和URL導航到ProjectComponentController'的'了'指數()'方法,而不是一個名爲'SaveComponent' –

+2

當我穿着藍色的褲子我的車無法啓動方法。 –

+0

親愛的斯蒂芬·馬克,感謝您的意見,是的,你是對的,我做了一個錯誤上。我沒有清楚地描述我的問題。有關詳細信息,我通過我的控制器中的ajax發佈了許多數據,接受需要作爲外鍵存儲在其他表中的project_id。所以我怎麼能在我的控制器中使用ASP.NET MVC中的View方法獲取ID? – ZKF3340320

回答

0

您可以隨時使用隱藏域和的jQuery/javscript更新它,並將其發送到後端的AJAX輔助.....

確保1.name應準確命名爲ActionMethod PARAM和3.Jquery,jQuery驗證和jQuery unobstrusive AJAX是正確加載

我的代碼.C SHTML

<script src="~/Scripts/jquery-2.1.4.min.js"></script> 
<script src="~/Scripts/jquery.validate.min.js"></script> 
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> 
<div> 
    @{ 
     AjaxOptions options = new AjaxOptions(); 
     options.HttpMethod = "POST"; 
     options.OnBegin = "OnBeginRequest"; 
     options.OnSuccess = "OnSuccessRequest"; 
     options.OnComplete = "OnCompleteRequest"; 
     options.OnFailure = "OnFailureRequest"; 
     // options.Confirm = "Do you want to Add Country ?"; 
     options.UpdateTargetId = "divResponse"; 
     options.InsertionMode = InsertionMode.InsertAfter; 
    } 
    @using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options)) 
    { 

     <input type="hidden" name="project_id" id="project_id" value="project_id" /> 
     <input type="submit" value="Click me" /> 

    } 
</div> 
<div id="divResponse"> 
</div> 
<script> 
    $(function() { 
     var url = window.location.href; 
     var array = url.split('/'); 

     var lastsegment = array[array.length - 1]; 
     console.log(lastsegment); 
     $('#project_id').val(lastsegment); 

    }); 
    function OnBeginRequest() { 
     console.log('On Begin'); 


    } 
    function OnCompleteRequest() { 
     console.log('On Completed'); 
    } 
    function OnSuccessRequest() { 
     console.log('On Success'); 

    } 
    function OnFailureRequest() { 
     console.log('On Failure'); 
    } 
</script> 

和控制器

[HttpPost] 
    public JsonResult AjaxSend(String project_id) 
    { 
     //rest goes here 
     return Json(new { Success = true }); 
    } 

這個鏈接可以幫助link

相關問題