简体   繁体   中英

How can i use a variable created within a view as an argument within an action result? (ASP.NET MVC)

Within my view i have a piece of JavaScript where i have declared a variable ' Fk '

<script>
     function test(clickedID) 
     {
          var Fk = clickedID;                        
     }
</script>

I want to be able to use 'Fk' within an action result by passing it as a parameter. For example:

[HttpPost]
        public ActionResult ReadFk(int Fk) //i would imagine id pass Fk to the ActionResult through the use of its paramaters..?
        {
            var dataFileFk = Server.MapPath("~/App_Data/ForeignKeyValue.txt");

            var textFileDataFk = Fk + Environment.NewLine;

            System.IO.File.WriteAllText(dataFileFk, textFileDataFk);

            return View();
        }

Is there an easy way of doing this? Thank you!

EDIT: Since you want to pass a variable from javascript to a controller action and you want to be redirected afterwards, you can use window.location.replace(url)

<script>
   function test(clickedID) 
   {
      var Fk = clickedID;  

      // this will redirect you to a controller action while sending data parameter
      window.location.replace("http://yoursite.com/ControllerName/WriteFK?data="+Fk);
   }
</script>

Then create an action that will receive the data and write that to the text file;

// remove HttpPost and change to ActionResult
public ActionResult WriteFK(string data)
{
   // variable data will contain the FK
   // write to text file here

   // return view
   return View();
}

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