如何从asp.net MVC控制器中的URL获取ID

时间:2016-09-24 05:54:17

标签: asp.net-mvc

我想从ASP.NET MVC Controller中的URL获取ID并将其插入到Project_ID中,下面是我的代码,我试过但它现在正在为我工​​作。

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;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

你可以随时使用隐藏字段并通过jquery / javscript更新它并将其发送到ajax帮助器的后端.....

确保1.name应该是ActionMethod param和3.Jquery,jQuery Validate和jQuery unobstrusive ajax正确加载的名称

我的代码.cshtml

<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

答案 1 :(得分:0)

您可以像这样从URL获取ID:

工资单:

html = $(data).find('.product-quantity-details .quantity');

查看:

public ActionResult Index(int id)
{
    ViewBag.ID = id;
    Your Code......
    return View(...);
}

} 现在,您在变量中有了一个ID