Hi I want to pass some data from an input tag to my module in NancyFx so I can add it to a json file. Looked everywhere for an answer but can't find anything.
VIEW
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<model>
@{
Layout = "Views/Shared/_Layout.cshtml";
}
<div id="addUser">
<form name="addUser" method="POST">
<p>First Name:</p>
<input type="text" name="user">
<input type="submit" name="Submit" value="Submit"/>
</form>
</div>
Module
public class LeaderboardModule : NancyModule
{
public LeaderboardModule()
{
Get["/adduser"] = _ =>
{
//var leaderboard = new LeaderboardModule();
//var users = new List<Users>();
//users = leaderboard.ReadFile("Users.json");
//users.Add(new Users() { Id = 7, Name = "John" });
//var lastItem = users.LastOrDefault();
//leaderboard.WriteFile("Users.json", users);
return View["Shared/_AddUser"];
};
Post["/adduser"] = _ =>
{
var leaderboard = new LeaderboardModule();
var users = new List<Users>();
users = leaderboard.ReadFile("Users.json");
users.Add(new Users() { Id = 7, Name = "John" });
//var lastItem = users.LastOrDefault();
leaderboard.WriteFile("Users.json", users);
return View["Leaderboard"];
};
}
public List<Users> ReadFile(string fileName)
{
var users = new List<Users>();
var readFile = File.ReadAllText(HttpContext.Current.Server.MapPath(fileName));
users = JsonConvert.DeserializeObject<List<Users>>(readFile);
return users;
}
public string WriteFile(string fileName, List<Users> users)
{
var newUser = JsonConvert.SerializeObject(users, Formatting.Indented);
File.WriteAllText(HttpContext.Current.Server.MapPath(fileName), newUser);
return newUser;
}
Here I just hard code the data in but I want to be able to add the data from the input on the view. Thanks.
I am assume the data you want to send back is whatever the user typed in the user
form field. In your POST
handler you can get to that like this:
Post["/adduser"] = _ =>
{
var user = Request.From.user;
// do stuff
return View["Leaderboard"];
}
Request
is a property on NancyModule
and Form
is a property on Request
of type DynamicDictionary
. When there are FORM
field in the HTTP POST
request they will be accessible in Request.Form
by the same name as they have on the page.
For small but working check out this, particularly this line.