如何从@Url 传递参数。动作到控制器函数

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

下面是参考编码:

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

以上代码未能将 id值传递给 CreatePerson函数。

290394 次浏览

你可以这样通过:

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

OR 也可以通过这种方式传递

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

如果你以这种方式通过:

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

这种将值从 Controller 传递到 View 的方式:

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"] })'" />
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));
@Url.Action("Survey", "Applications", new { applicationid = @Model.ApplicationID }, protocol: Request.Url.Scheme)
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})';

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

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!");
}
});

试试这个

public ActionResult CreatePerson(string Enc)


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

您将得到 Enc 字符串中的 id。

试试这个:

public ActionResult CreatePerson(int id) //controller


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

传递参数正常。

需要两个或多个参数通过抛出视图控制器使用此语法..。 试试... 它。

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;