I want get a values from web client and save it in database, but I don't know how call my controller methods from cshtml
#{
#ViewBag.Title;
#model Homi.Controllers.HomeController
Homi.Controllers.HomeController obj = (Homi.Controllers.HomeController)ViewData["h"];
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
#Styles.Render("~/Content/style.css")
#Styles.Render("~/Content/rest.css")
#Styles.Render("~/Content/font.css")
#Styles.Render("~/Content/font2.css")
</head>
<body>
Register
<div>
<input type="username" id="Username required="required" />
</div>
<div>
<input type="password" id="Password" required="required" />
<label for="Password">Password</label>
</div>
<div>
<input type="password" id="Repeat Password" required="required"/>
<label for="Repeat Password">Repeat Password</label>
</div>
<div>
<button><span>Next</span></button>
</div>
#Scripts.Render("~/Content/index.js")
#Scripts.Render("~/Content/jquery.js")
</body>
</html>
for example I have this code on my mind but you know it's doesn't work:
<div onclick=#obj.setp(username.text, password.text)>
<button><span>Next</span></button>
</div>
I want when I click on "Next" button my method calling.
and this is part of my controller, the method that I want to call:
namespace Homi.Controllers{
public class HomeController : Controller
{
public ActionResult setp(string usename, string password)
{
WebAdmin wa = new WebAdmin();
wa.InsertToDb(username, password);
return View("userAccess");
}}}
it's very important to me that I don't change my html code style
thank you for your help
Keep your input fields inside a form tag and submit the form
#using(Html.BeginForm("setp","home"))
{
<input type="text" name="Username" required="required" />
<input type="text" name="Password" required="required" />
<input type="submit" value="Next"/>
}
When razor executes the page, it will generate a form tag in the place of #using(Html.BeginForm line where the action is set to "home/setp"(Check the view source in browser). As long as your form element name's matches with your HttpPost action method parameter name's, values of the textboxes will be available in those when the form is submitted.
[HttpPost]
public ActionResult setp(string Username, string password)
{
//do something
}
Related
Making a little search engine. The idea is to take input from the user and then based on that, make a redirection to the search page.
The following code:
<form action ="/search.html">
<label for="form-search"></label>
<input type="text" id="form-search" placeholder="TYPE HERE!"><hr>
<input type="submit" name="query" value="Search!">
</form>
Always redirects to the following page regardless of what the input user has given:
/search.html?query=++Search%21++
While (for the input "Suppose This Was Entered") it should go to:
/search.html?query=Suppose++This++Was++Entered
Any help will be appreciated.
The var name used in the query string of the url is the name attribute of the form fields so you need add a name atribute to your text field instead to the submit input.
<form action ="/search.html">
<label for="query"></label>
<input type="text" id="query" name="query" placeholder="TYPE HERE!"><hr>
<input type="submit" value="Search!">
</form>
The id and the name in the text field not necessary has to be the same
You can create a function that gets called when the form submits via the form's onsubmit attribute. From within the funciton you can manipulate your URL generation like below:
Note: return false; is to prevent submitting the form since the return value of the function is passed to the form's onsubmit.
function submitFunction() {
let searchText = document.getElementById("form-search").value.trim();
let form = document.getElementById('myForm');
if(searchText.length > 0) {
document.getElementById("s").value = searchText;
form.action = "/search.html";
form.submit();
} else {
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Title of Your page</title>
</head>
<body>
<form id="myForm" method="get" onsubmit="return submitFunction();">
<label for="form-search"></label>
<input type="text" id="form-search" placeholder="TYPE HERE!" value="" >
<input type="hidden" id="s" name="query" value="" />
<hr>
<input type="submit" value="Search!">
</form>
</body>
</html>
I have the code below that shows my Create cshtml page and the controller connected to it.
It's working fine, however now I need to add another field to the form that is not in the GameManagement.Game model.
This field is called "CreatorUserId" and does not exist in the model I'm using.
But I do I get the value of this field, and then pass it into the controller when it's not part of the model?
Thanks!
Create.cshtml:
#model GameManagement.Game
<div>
<div>
<form asp-action="Create">
<div>
<label asp-for="Id"></label>
<input asp-for="Id" />
</div>
<div>
<label asp-for="Description"></label>
<input asp-for="Description" />
</div>
<div>
<label asp-for="DisplayName"></label>
<input asp-for="DisplayName" />
</div>
<div>
<label>Creator User ID</label>
<input id="CreatorUserId" />
<div>
<input type="submit" value="Create" />
</div>
</form>
</div>
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Description,DisplayName")] Game newGame)
{
// code to send the form information (Id, Description, DisplayName) to a 3rd party API
apiResult = await apiClient.createNewGame(
newGame.Id,
newGame.Description,
newGame.DisplayName,
// CreatorUserId ?? not in Game model....
return View(apiResult);
}
As #johnluke.laue suggested , the best solution is to create a new view model to include the needed properties .
If you insist on not creating a new viewmodel , the workaround could be add name attribute :
<input id="CreatorUserId" name="CreatorUserId" />
And get value on server side like :
public async Task<IActionResult> Create([Bind("Id,Description,DisplayName")] Game newGame, string CreatorUserId)
{
}
Although I am studying the Java Servlet and JSP from Murach and I have a question about HTML format haha
After submiting a form on index.jsp, the EmailListServlet is called, it does some validation and if everything is ok the thanks.jsp in called.
Index.jsp file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Murach's Java Servlets and JSP</title>
<link rel="stylesheet" href="styles/main.css" type="text/css"/>
</head>
<body>
<h1>Join our email list</h1>
<p>To join our email list, enter your name and
email address below.</p>
<p><i>${message}</i></p>
<form action="emailList" method="post">
<input type="hidden" name="action" value="add">
<label class="pad_top">Email:</label>
<input type="email" name="email" value="${user.email}"
required><br>
<label class="pad_top">First Name:</label>
<input type="text" name="firstName" value="${user.firstName}"
required><br>
<label class="pad_top">Last Name:</label>
<input type="text" name="lastName" value="${user.lastName}"
required><br>
<label> </label>
<input type="submit" value="Join Now" class="margin_left">
</form>
</body>
</html>
EmailLisServlet
package murach.email;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import murach.business.User;
import murach.data.UserDB;
public class EmailListServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String url = "/index.html";
// get current action
String action = request.getParameter("action");
if (action == null) {
action = "join"; // default action
}
// perform action and set URL to appropriate page
if (action.equals("join")) {
url = "/index.jsp"; // the "join" page
}
else if (action.equals("add")) {
// get parameters from the request
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
// store data in User object
User user = new User(firstName, lastName, email);
// validate the parameters
String message;
if (UserDB.emailExists(user.getEmail())) {
message = "This email address already exists.<br>" +
"Please enter another email address.";
url = "/index.jsp";
}
else {
message = "";
url = "/thanks.jsp";
UserDB.insert(user);
}
request.setAttribute("user", user);
request.setAttribute("message", message);
}
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
thanks.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Murach's Java Servlets and JSP</title>
<link rel="stylesheet" href="styles/main.css" type="text/css"/>
</head>
<body>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<label>Email:</label>
<span>${user.email}</span><br>
<label>First Name:</label>
<span>${user.firstName}</span><br>
<label>Last Name:</label>
<span>${user.lastName}</span><br>
<p>To enter another email address, click on the Back
button in your browser or the Return button shown
below.</p>
<form action="" method="post">
<input type="hidden" name="action" value="join">
<input type="submit" value="Return">
</form>
</body>
</html>
The question is I didn't understand why when I submit the form on the thanks.jsp it returns to index.jsp once the action element is empty.
Could you tell me what I'm letting go?
I have a form with all fields, less one of it, filled from user. This is the class passed through the form
public class CarForm {
private String id;
private Integer initialKm;
private String carChassis;
private String note;
private String carType;
private Integer fleet;
The only one field, fleet, I would like to set before pass the form, or better, set it from HTML. For example:
<div class="form-group">
<label>Fleet application</label> <input type="text"
class="form-control" th:field="*{fleet}"
th:placeholder="${fleetApplication}" readonly="readonly">
</div>
So I would like to show ${fleetApplication.application} and set into fleet this value, or, if it is possible, set another value${fleetApplication.idFleet}.
Is it possible one of these solutions?Thanks
Update: as suggested by #Faraj Farook I resolved so:
<div class="form-group">
<label>Fleet application</label>
<!-- Show fleet application -->
<input class="form-control" type="text" th:value="${fleetApplication.application}" readonly="readonly" />
<!-- Save into fleet the value of idFleet -->
<input type="hidden" name="fleet" th:value="${fleetApplication.idFleet}" />
</div>
Setting it in the server side
controller
String action(Model model){
CarForm carForm = new CarForm();
carForm.setFleet(<some value>);
model.addAttribute("obj", carForm);
return view.html;
}
view.html
<div class="form-group">
<label>Fleet application</label>
<input type="text" th:field="*{fleet}" readonly/>
</div>
setting it in the client side
view.html
<div class="form-group">
<label>Fleet application</label>
<input type="text" readonly th:value="${someValueVariable}"/>
<input type="hidden" name="fleet" th:value="${someValueVariable}"/>
</div>
I have this HTML5 code:
<form id="LogInArea" action = "/Home/ValidateUser" >
<fieldset>
<legend>Login Page</legend>
<p>
<label>
User name<br>
<input type="text" id="userName" required></label></p>
<p><label>
Password<br>
<input type="password" id="password" required></label></p>
<p>#*<button id="LoginButton">
Log in</button>*#
<button>submit</button>
</p>
Register if you don't have an account.
</fieldset>
</form>
When I press the submit button the ValidateUser() action in Home controller is fired.
My question is how can I get the submitted form in ValidateUser() action and how I get the values of form element?
P.S. I don't want to use model!
I'm not sure why you don't want to use a model as the other answers recommend, however you can get the form values by using the Request object.
[HttpPost]
public void ValidateUser()
{
string name = Request.Form["userName"];
string password = Request.Form["password"];
}
However you will need ensure that you set your form method to Post and add name values to all your submitted form fields.
<form id="LogInArea" action = "/Home/ValidateUser" method="post">
...
<input type="text" id="userName" name="userName" required></label>
...
<input type="password" id="password" name="password" required></label>
...
</form>
You should also define a value for the 'name' attribute, so instead of:
<input type="text" id="userName" required>
it should be
<input type="text" id="userName" name="username" required>
then in your controller:
public ActionResult ValidateUser(string username)
{
...
}
You have to catch model you passed into your view i.e.
If you have passed Login model into your view, then you have to catch same into your controller's action method like below:
public ActionResult Login(Login model)
{
// Login is your model which you passed into view. Validate it here.
}
To get values you have to use name attribute in your input tag.
Let me know if you have any confusion.