简体   繁体   中英

Passing a null parameter from the model to an action in the controller

I am doing an asp .net mvc apllication and i have some problem : i have this view that contains a link to an action

<form >
    <fieldset>
        <legend>Formulaire d'un client</legend>
        @if (Model.Count != 0){
       foreach (string s in Model)
    {
    <a href="@Url.Action("Passer", "Client",(object)@s)"  style="color:blue" >@s</a>
    <br />
      }
        }
        else{
        <label> Pas de projets actuellement</label>
        }
      </fieldset>
  </form>

it called this action :

public ActionResult Passer(string s)
       {


               Upload.Models.ProjetModels prj = new ProjetModels();
               Upload.Models.CompteModels.Id_directory = prj.GetProjectsId(s);
               int _id_directory = Upload.Models.CompteModels.Id_directory;
               int _id_akeo = prj.GetAkeoIdFromProjet(_id_directory);
               int _id_client = Upload.Models.CompteModels.Id_connected;
               Upload.Models.AkeoModels ak = new AkeoModels();
               string _nom_akeo = ak.GetNameAkeoByID(_id_akeo);

               Upload.Models.DetailsModels detail = new DetailsModels { Id_akeo = _id_akeo, Id_client = _id_client, Id_directory = _id_directory, Nom_akeo = _nom_akeo };
               return View(detail);

       }

My problem is the parameter s , it is always null when i click into the link.

Why this happens? How can i correct it?

My problem is the parameter s , it is always null when i click into the link.

Because your link will look like /Client/Passer/123 . You could've seen this by looking at the generated HTML, by using Fiddler to debug the HTTP requests or by looking at the browser's address bar after clicking the link.

Url.Action() 's third parameter, routeValues , is an object that gets mapped to the parameters of the actionmethod that gets invoked. Since your ActionResult Passer 's signature is string s , you'll need to pass an object that has a string property named s .

So change

(object)@s

To

new { s = s }

The latter will cause an anonymous object to be created, containing a single string s property containing the value of s . You might want to look into your variable naming.

Try this,

@Url.Action("Passer", "Client", new {s = s})

You were not passing arguments as route value. Visit link for elaboration.

Ref: http://msdn.microsoft.com/en-us/library/dd460348(v=vs.108).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM