Value Undefined In React.JS View ASP.NET MVC - asp.net-mvc

I am Making a Lib Managment System to Add Books to My DB.
I am doing this through ASP.NET MVC AND my view is in REACT.JS
My Controller for CREATE BOOK is :
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "BookName,BookSerialNumber,BookAuther,BookPublisher")] Book book)
{
using (LibraryManagmentSystemDBEntities db = new LibraryManagmentSystemDBEntities())
if (ModelState.IsValid)
{
db.Books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
My view which is in React.js is as follows
Error is coming Uncaught TypeError: Cannot read property 'value' of undefined
I have also added a screen shot so that it is easier to point my mistake out.
<div id="app" class="container">
</div>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/babel">
class InputValues extends React.Component
{
constructor(props)
{
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e)
{
e.preventDefault();
const data = new FormData();
data.append('BookName', this.BookName.value);
data.append('BookSerialNumber', this.BookSerialNumber.value);
data.append('BookAuther', this.BookAuther.value);
data.append('BookPublisher', this.BookPublisher.value);
var xhr = new XMLHttpRequest();
xhr.open('post', this.props.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function()
{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200)
{
alert("good!!!");
}
}
xhr.send(data);
}
render()
{
return(
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="BookName">Book Name </label><br />
<input id="BookName" type="text" placeholder="Enter BookName" ref={this.BookName} />
<br /><br />
<label htmlFor="BookSerialNumber">Book Serial Number: </label><br />
<input id="BookSerialNumber" type="text" placeholder="Enter BookSerialNumber" ref={this.BookSerialNumber} />
<br /><br />
<label htmlFor="BookAuther">BookAuther: </label><br />
<input id="BookAuther" type="text" placeholder="BookAuther" ref={this.BookAuther} />
<br /><br />
<label htmlFor="BookPublisher">BookPublisher: </label><br />
<input id="BookPublisher" type="text" placeholder="Enter BookPublisher" ref={this.BookPublisher} />
<br /><br />
<p>
<button type="submit">Submit</button>
</p>
</form>
</div>
);
}
}
ReactDOM.render
(<InputValues />, document.getElementById("app"));
</script>

Related

How to get Input control value in controller's Index method asp.net core

I am working on captcha authentication. I want to get user entered captcha value in controller's Index method. Below is my cshtml file code
#{
ViewData["Title"] = "Home Page";
}
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br/>
<button class="button" type="submit">Login</button>
<br />
</div>
When user entering captcha value in txtCapValue and click submit button I need that value in controller. Here is my controller
public IActionResult Index()
{
randnumber = RandomString(6);
ViewData["captcha"] = randnumber;
return View();
}
how can I get txtCapValue input control value when user click on submit button ?
One of the easy ways using the Form Tag Helper:
<form asp-controller="Controller_Name" asp-action="Captcha" method="post">
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button class="button" type="submit">Login</button>
<br />
</div>
</form>
And on the server side:
[HttpPost]
public IActionResult Captcha(string cap)
{
... using the `cap`
return View("Index");
}
I want to get user entered captcha value in controller's Index
method.
There are two options, you can try:
Option1: use Form Tag Helper
Index method:
public IActionResult Index(string cap)
{
ViewData["captcha"] = 6;//do your staff
return View();
}
Index view:
<form method="get" asp-action="Index">
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button class="button" type="submit">Login</button>
<br />
</div>
</form>
Option 2: use ajax
Index method:
public IActionResult Index(string cap)
{
ViewData["captcha"] = 6;
return View();
}
Index view:
<div class="container">
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblshowCaptcha"><b>#ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button id="buttonDemo1" class="button" type="submit">Login</button>
<br />
</div>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#buttonDemo1').click(function () {
var cap = $("#txtCapValue");
$.ajax({
type: 'GET',
url: '/Home/Index',
data: cap
});
});
});
</script>
}
result:

MVC Template editors and post

I'm at a beginner with ASP.NET MVC 4 and I have a problem. Basically I have this controller:
public ViewResult Login()
{
return View(new LoginViewModel());
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
if (authProvider.Authenticate(model.LoginUserName, model.LoginPassword))
{
return Redirect(Url.Action("Index", "Home"));
}
TempData["message"] = "Nome utente e/o password errati!!!";
return View();
}
return View();
}
That implements a simple login view. I created also a ViewModel:
public class LoginViewModel
{
[Required(ErrorMessage = "Il nome utente è obbligatorio")]
[UIHint("TextBoxLogin")]
public string LoginUserName { get; set; }
[Required]
public string LoginPassword { get; set; }
}
Finally I created the EditorTemplate:
#model string
<input name="#ViewData.TemplateInfo.HtmlFieldPrefix" id="#ViewData.TemplateInfo.HtmlFieldPrefix"data-validation="required" data-validation-error-msg="#ViewData["HelpMessage"]" value="#Model" />
So far so good. The problem is in the view. If I put this in the view:
#using(Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.EditorForModel()
<p><input type="submit" value="Log in" /></p>
}
It works like a charm (but it puts a lot of not wanted html into the page), in fact, when I click on the submit button it goes to the POST actionResult of the controller. If I put this:
#using (Html.BeginForm("Login","Account",FormMethod.Post))
{
<p class="username">
<label for="UserName">Nome utente</label>
#Html.EditorFor(m => m.LoginUserName, new { HelpMessage = "Il nome utente è obbligatorio!!!" });
</p>
<p class="password">
<label for="Password">Password</label>
#Html.EditorFor(m => m.LoginPassword)
</p>
<p>
<input type="submit" value="Log in" />
</p>
}
It does not go on the post actionresult but always on the Get one. I want to put this type of code (the last one) in wich I can setup exactly the html but I want that it goes on the POST Actionresult, can someone help me to understand why?
-----------------update----------------
Here is the HTML generated:
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>Title</title>
<meta name="robots" content="noindex,nofollow" />
<link href="/static/css/login.css" rel="stylesheet" type="text/css" />
<link href="/static/css/jquery_ui.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]><link href="/static/css/lt_ie9.css" rel="stylesheet" type="text/css" /><![endif]-->
<script src="/static/js/jquery_1_10_2.js"></script>
<script src="/static/js/jquery_ui.js"></script>
<script src="/static/js/jquery_ui_function.js"></script>
</head>
<body>
<form>
<div id="top">
<div class="wrapped">
<div id="logo">TITLE</div>
</div>
</div>
<div id="content" class="user_student">
<div class="wrapped">
<div class="login_intro">
<h2>TEST</h2>
</div>
<div class="login_input">
<p id="error_messages"></p>
<h2>THIS ONE MAKES GET REQUEST</h2>
<form action="/Account/Login" method="post"> <p class="username"><label for="UserName">Nome utente</label>
<!--<input id="UserName" name="UserName" type="text"/>-->
<input name="LoginUserName" id="LoginUserName"data-validation="required" data-validation-error-msg="Il nome utente è obbligatorio!!!" />;
</p>
<p class="password"><label for="LoginPassword">Password</label>
<input class="text-box single-line" data-val="true" data-val-required="Il campo LoginPassword è obbligatorio." id="LoginPassword" name="LoginPassword" type="text" value="" />
</p>
<p><input type="submit" value="Log in" /></p>
</form> <p class="hidden">old</p>
</div>
<div class="login_footer">
<p>FOOTER</p>
</div>
</div>
</div>
<h2>THIS ONE MAKE POST REQUEST</h2>
<form action="/Account/Login?ReturnUrl=%2f" method="post"><div class="editor-label"><label for="LoginUserName">LoginUserName</label></div>
<div class="editor-field"><input name="LoginUserName" id="LoginUserName"data-validation="required" data-validation-error-msg="" /> <span class="field-validation-valid" data-valmsg-for="LoginUserName" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="LoginPassword">LoginPassword</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-required="Il campo LoginPassword è obbligatorio." id="LoginPassword" name="LoginPassword" type="text" value="" /> <span class="field-validation-valid" data-valmsg-for="LoginPassword" data-valmsg-replace="true"></span></div>
<p><input type="submit" value="Log in" /></p>
</form><script src="/static/form-validator/jquery.form-validator.min.js"></script>
<script src="/static/js/jquery_form_validator_function.js"></script>
</form>
</body>
</html>
Finally I figured out what is the problem...and of course it is the most stupid thing in the world.
In the rended code there is a open just after the body and, inside it, the form that MVC put from razor view.
Thanks for everyone for the help paricularly to #DavidG

Httppost not firing in mvc

I have two buttons on a page and I want the user to click one and they both go to different pages, the problem is my httpPost attribute is not firing.
Here is my controller:
public ActionResult Index()
{
if (Session["AccountConfirmationViewModel"] != null)
{
AccountConfirmationViewModel accountConfirmationViewModel = Session["AccountConfirmationViewModel"] as AccountConfirmationViewModel;
if (accountConfirmationViewModel == null || !TryValidateModel(accountConfirmationViewModel))
{
return RedirectToAction("AccountSearch", "Home");
}
MobileStep1ViewModel mobileModel = new MobileStep1ViewModel();
mobileModel.GetMobileNumbers(accountConfirmationViewModel.CustomerReferenceNumber);
Session["MobileModel"] = mobileModel;
}
return View();
}
[HttpPost]
public ActionResult Index(string button)
{
if (button == "btnNotMobileQuery")
{
RedirectToAction("AcconutSearch", "Home");
}
else if (button == "btnMobileQuery")
{
RedirectToAction("SecurityQuestion", "Mobile");
}
return View();
}
Here is my view:
#model OutsourcedTicketPlatform.UI.ViewModels.Mobile.MobileStep1ViewModel
#using OutsourcedTicketPlatform.UI.ViewModels.Mobile
#{
MobileStep1ViewModel mobileModel = Session["MobileModel"] as MobileStep1ViewModel;
ViewBag.Title = "Mobile Issue";
}
<h2>Mobile Issue Reporter</h2>
<p>Hi #mobileModel.CustomerName are you phoning today to log the mobile device as lost or stolen?</p>
#Html.RadioButton("IsMobileQuery", "MobileQuery")Yes
#Html.RadioButton("IsMobileQuery", "NotMobileQuery")No
<br /><br />
<div id="NotMobileQuery" class="HideDiv">
<input type="submit" class="btn" id="btnNotMobileQuery" value="Proceed" />
</div>
<div id="ConfirmMobile" class="HideDiv">
<p>"Please Confirm your mobile number"</p>
#foreach (var items in mobileModel.MobileNumbers)
{
#Html.RadioButton("SelectedMobileNumber", items)#items
}
<br /><br />
<input type="submit" class="btn" id="btnMobileQuery" value="Next" />
</div>
<script src="../../Scripts/Controllers/Mobile/MobileStepOne.js" type="text/javascript"></script>
<script src="../../Scripts/ViewModels/Mobile/MobileStepOneViewModel.js" type="text/javascript"></script>
Can anyone see if I am doing anything wrong? Do I need parameter in my second index method?
Try this :
#model OutsourcedTicketPlatform.UI.ViewModels.Mobile.MobileStep1ViewModel
#using OutsourcedTicketPlatform.UI.ViewModels.Mobile
#{
MobileStep1ViewModel mobileModel = Session["MobileModel"] as MobileStep1ViewModel;
ViewBag.Title = "Mobile Issue";
}
#using(Html.BeginForm("Index","Your_controller_name",FormMethod.Post)){
<h2>Mobile Issue Reporter</h2>
<p>Hi #mobileModel.CustomerName are you phoning today to log the mobile device as lost or stolen?</p>
#Html.RadioButton("IsMobileQuery", "MobileQuery")Yes
#Html.RadioButton("IsMobileQuery", "NotMobileQuery")No
<br /><br />
<div id="NotMobileQuery" class="HideDiv">
<input type="submit" class="btn" id="btnNotMobileQuery" value="Proceed" />
</div>
<div id="ConfirmMobile" class="HideDiv">
<p>"Please Confirm your mobile number"</p>
#foreach (var items in mobileModel.MobileNumbers)
{
#Html.RadioButton("SelectedMobileNumber", items)#items
}
<br /><br />
<input type="submit" class="btn" id="btnMobileQuery" value="Next" />
</div>
}
<script src="../../Scripts/Controllers/Mobile/MobileStepOne.js" type="text/javascript"></script>
<script src="../../Scripts/ViewModels/Mobile/MobileStepOneViewModel.js" type="text/javascript"></script>
You can use FormCollection instead of string for getting all values form view.

JQueryValidation with MVC 4 not validating on blur

I am beating my head on the wall for hours with MVC 4 and jQuery validation to validate the first first on blur. I have tried attaching the validation to the entire form AND to the individual element (first field) to no avail. If I add an alert() into the blur event it seems to fire but no validation of the required field. I have additional validations to add after the required is working but haven't gotten to them yet. I don't know that it is a problem with the MVC 4. JQueryvalidate is v1.10. I have also tried setting up the validator and then calling .valid() on the element I want validated using the .blur and still not validation that I can see.
$(function () {
$('#productionOrder').focus();
$.validator.addMethod("cMinLength", $.validator.methods.minlength,
$.format("Must contain as least {0} chars"));
$.validator.addClassRules("productionOrder", { cMnLength: 3 });
$('#myForm').validate({
onkeyup: false,
//onfocusout: false,
errorClass: 'fieldError'
//rules: {
// productionOrder: "required number",
// tc: "required",
// dn: "required"
//}
});
$("#towCount").bind("change keyup", function () {
$form.validate().element("#towCount");
});
//$('#productionOrder').validate({
// //onkeyup: false,
// onfocusout: false,
// errorClass: 'fieldError',
// rules: {
// productionOrder: {
// required: true
// }
// }
//});
});
And the .cshtml
#model FiberLine2.ViewModels.Creel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<style>
.fieldError {
border-color: red;
border-width: medium;
}
.input-label {
font-size: 13px;
width: 130px;
height: 30px;
display: inline-block;
}
</style>
</head>
<body>
<form id="myForm">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div>
<!-- app header -->
<label>#Resources.Strings.User: </label>
<label>#User.Identity.Name</label>
</div>
<fieldset>
<legend>#Resources.Strings.Creel #Resources.Strings.Load</legend>
<div>
<div id="errorDiv"></div>
<hr />
#Html.Label(#Resources.Strings.ProductionOrder, new { #class = "input-label lock" })
<input type="text" id="productionOrder" name="productionOrder" class="required" maxlength="4" />
<br />
<label class="input-label lock">#Resources.Strings.Tow #Resources.Strings.Count</label>
<input type="text" id="towCount" name="tc" class="required" size="5" maxlength="5" value="299" />
<br />
<label class="input-label lock">#Resources.Strings.Batch #Resources.Strings.Sequence</label>
<input type="text" id="doffNumber" name="dn" size="5" maxlength="5" value="1" />
<br />
<label class="input-label">#Resources.Strings.Creel #Resources.Strings.Position</label>
<input type="text" id="creelPosition" name="cp" size="5" maxlength="5" />
<br />
<label class="input-label">#Resources.Strings.Batch #Resources.Strings.ID</label>
<input type="text" id="creelNumber" name="cn" size="7" maxlength="7" />
<br />
<hr />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
</body>
</html>
Can you try this instead?
var settngs = $.data($('#myForm')[0], 'validator').settings;
settngs.onkeyup = false;

How to display wrong username password on login form ?

I am developing the MVC application.
I have designed the login form.
when user enters the proper username and password then, it redirect to next page, but when user put wrong username or password I want to display the message on the login form, how to do it.
This is the code of method in controller...
[HttpPost]
public ActionResult LoginUser(FormCollection oFormCollection)
{
string userName = oFormCollection["username"];
string password = oFormCollection["password"];
bool IsAccountPerson = false;
var validEmployee = (from e in db.Employees
where e.UserName == userName && e.Password == password
select e).ToList();
if (validEmployee.Count() == 1)
{
foreach (var v in validEmployee)
{
oEmployee = v;
Session["LoggedEmployee"] = oEmployee;
Session["loggedEmpId"] = oEmployee.Id;
if (oEmployee.DesignationType == "Account")
{
IsAccountPerson = true;
}
else
{
IsAccountPerson = false;
}
}
if(IsAccountPerson)
return RedirectToAction("PaymentAdviceListForAccounts", "Account");
else
return RedirectToAction("Index", "PaymentAdvice");
}
else
return PartialView("Index");
}
and this is my view Code....
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="#Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
<title></title>
</head>
#using (Html.BeginForm("LoginUser","Login",FormMethod.Post))
{
#*<div style="margin:15% 20% 20% 30%; width:35%;min-height:25%;border:1px #ACACAC solid;">*#
<div class="container-fluid" style="padding-left:0px; margin-top:165px; margin-left:140px;">
<div class ="span3">
<label style="font-size:15px; color:#666666; margin-top:5px;">Username</label>
</div>
<div class ="span6">
<input type="text" id="username" name="username" style="height:20px; width:100%;" />
</div>
<div class ="span3">
<label style="font-size:15px;color:#666666; margin-top:5px; ">Password</label>
</div>
<div class ="span6">
<input type="password" id="password" name="password" style="height:20px; width:100%;"/>
</div>
<div class="span6" style="padding-left:15px;">
<input type="submit" name="submit" value="Login" class="btn btn-primary" style="margin-right:10px; height:30px; font-size:14px; width:55px;" />
<input type="button" name="Login" value="Cancel" class="btn btn-primary" style="margin-right:20px; height:30px; font-size:14px; width:55px; padding-left:5px; padding-right:5px;" />
</div>
</div>
</div>
</div>
</div>
}
</body>
</html>
create new model or use TempData.
here is the example using TempData.
http://www.devcurry.com/2012/05/what-is-aspnet-mvc-tempdata.html

Resources