[c#] how to pass parameter from @Url.Action to controller function

I have a function CreatePerson(int id) , I want to pass id from @Url.Action.

Below is the reference code:

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

the above code fails to pass id value to CreatePerson function.

This question is related to c# asp.net-mvc

The answer is


If you are using Url.Action inside JavaScript then you can

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

This way to pass value from Controller to View:

ViewData["ID"] = _obj.ID;

Here is the way to pass value from View to Controller back:

<input type="button" title="Next" value="Next Step" onclick="location.href='@Url.Action("CreatePerson", "Person", new { ID = ViewData["ID"] })'" />

should you pass it in this way :

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

Try this

public ActionResult CreatePerson(string Enc)

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

you will get the id inside the Enc string.


Try this:

public ActionResult CreatePerson(int id) //controller 

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

it's working fine passing parameter.


you can pass it this way :

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

OR can also pass this way

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

@Url.Action("Survey", "Applications", new { applicationid = @Model.ApplicationID }, protocol: Request.Url.Scheme)

Need To Two Or More Parameters Passing Throw view To Controller Use This Syntax... Try.. It.

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;

public ActionResult CreatePerson(int id) //controller 

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

Or

var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = 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));