I am facing a problem getting the values from my form and passing it to the controller.
AddUser.cshtml
@model SecureMedi.Models.Users
<form asp-controller="Index" asp-action="AddUser" method="post">
<div class="form-group">
<label asp-for="Username">Username</label>
<input asp-for="Username" class="form-control" />
</div>
<!-- / form-group -->
<div class="form-group">
<label asp-for="Role">Username</label>
<input asp-for="Role" class="form-control" />
</div>
<!-- / form-group -->
<button type="submit" class="btn btn-primary">Add User</button>
</form>
<!-- / form -->
UsersDAL.cs (Data access layer)
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using SecureMedi.Models;
namespace SecureMedi.DAL {
public class UsersDAL {
public void Insert(Users u) {
string connectionstring = "MY_CONNECTION_STRING";
SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(String.Format("CREATE USER {0} WITHOUT LOGIN", u.Username), conn);
SqlCommand cmd2 = new SqlCommand(String.Format("ALTER ROLE {1} ADD MEMBER {0}", u.Username, u.Role), conn);
try {
conn.Open();
using(conn) {
cmd.Transaction = conn.BeginTransaction();
cmd.ExecuteNonQuery();
cmd2.Transaction = cmd.Transaction;
cmd2.ExecuteNonQuery();
cmd2.Transaction.Commit();
}
} finally {
if (conn != null) {
conn.Close();
}
}
}
}
}
Users.cs (Model)
namespace SecureMedi.Models {
public class Users {
public string Username {
get;
set;
}
public string Role {
get;
set;
}
}
}
HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using nmvs_db.dal;
using nmvs_module;
using nmvs_module.util;
using SecureMedi.Models;
using SecureMedi.DAL;
namespace SecureMedi.Controllers
{
public class HomeController : Controller
{
public ActionResult AddUser(Users u)
{
UsersDAL ud = new UsersDAL();
ud.Insert(u);
return View(u);
}
}
}
Here, I am facing two problems:
1) Whenever I navigate to /AddUser in my browser the AddUser method is called automatically. Instead, I would like to call AddUser method only when the form button is clicked.
2) Since AddUser is called (point 1) automatically the values I am retrieving from u.Username and u.Role is null.
For debugging purposes, if I modify my controller method like following:
public ActionResult AddUser(Users u) {
if (u.Username == null)
u.Username = "testuser";
if (u.Role == null)
u.Role = "SecureMediUsers";
UsersDAL ud = new UsersDAL();
ud.Insert(u);
return View(u);
}
The only values which are passed in the DAL are the hardcoded values of Username and Role as shown above, where I want those values to be fetched from the form input values.
[HttpPost]public ActionResult AddUser() { return View(); }method for the GET callGETcall too before I post some action. By the way, how would I return to another route after the POST call is made using[HttpPost] AddUser()method? I also like you to post this as an answer so that I accept it.