72

我有一个函数CreatePerson(int id),我想id@Url.Action.

下面是参考代码:

public ActionResult CreatePerson(int id) //controller 
window.location.href = "@Url.Action("CreatePerson", "Person") + id";

上面的代码无法将id值传递给CreatePerson函数。

4

10 回答 10

122

你可以这样传递:

Url.Action("CreatePerson", "Person", new RouteValueDictionary(new { id = id }));

OR也可以通过这种方式

Url.Action("CreatePerson", "Person", new { id = id });
于 2012-10-22T18:33:26.170 回答
28
public ActionResult CreatePerson (string id)

window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID",id);

public ActionResult CreatePerson (int id)

window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID", parseInt(id));
于 2015-10-27T15:04:37.383 回答
5
public ActionResult CreatePerson(int id) //controller 

window.location.href = '@Url.Action("CreatePerson", "Person")?id=' + id;

或者

var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = id})';
于 2016-12-16T15:43:13.843 回答
4

尝试这个:

public ActionResult CreatePerson(int id) //controller 

window.location.href = "@Url.Action("CreatePerson", "Person")?Id='+Id+'";

它工作正常传递参数。

于 2018-09-11T10:06:53.687 回答
2

这种将值从控制器传递到视图的方式:

ViewData["ID"] = _obj.ID;

这是将值从 View 传递回 Controller 的方法:

<input type="button" title="Next" value="Next Step" onclick="location.href='@Url.Action("CreatePerson", "Person", new { ID = ViewData["ID"] })'" />
于 2015-08-12T07:53:16.377 回答
2

需要两个或更多参数将视图传递给控制器​​使用此语法...尝试..它。

var id=0,Num=254;var str='Sample';    
var Url = '@Url.Action("ViewNameAtController", "Controller", new RouteValueDictionary(new { id= "id", Num= "Num", Str= "str" }))'.replace("id", encodeURIComponent(id));
    Url = Url.replace("Num", encodeURIComponent(Num));
    Url = Url.replace("Str", encodeURIComponent(str));
    Url = Url.replace(/&amp;/g, "&");
window.location.href = Url;
于 2018-10-23T06:07:25.293 回答
1

尝试这个

public ActionResult CreatePerson(string Enc)

 window.location = '@Url.Action("CreatePerson", "Person", new { Enc = "id", actionType = "Disable" })'.replace("id", id).replace("&amp;", "&");

您将在 Enc 字符串中获得 id。

于 2017-12-19T05:04:11.687 回答
0

你应该以这种方式传递它:

public ActionResult CreatePerson(int id) //controller 
window.location.href = "@Url.Action("CreatePerson", "Person",new { @id = 1});
于 2015-04-06T18:35:44.020 回答
0

如果您Url.Action在 JavaScript 内部使用,那么您可以

var personId="someId";
$.ajax({
  type: 'POST',
  url: '@Url.Action("CreatePerson", "Person")',
  dataType: 'html',
  data: ({
  //insert your parameters to pass to controller
    id: personId 
  }),
  success: function() {
    alert("Successfully posted!");
  }
});
于 2017-08-14T05:41:26.370 回答
0
@Url.Action("Survey", "Applications", new { applicationid = @Model.ApplicationID }, protocol: Request.Url.Scheme)
于 2016-09-06T12:21:03.730 回答