Httppost not firing in mvc - asp.net-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.

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:

Value Undefined In React.JS View 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>

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

ASP.NET MVC2, can I use a model field as an html id?

I am a newbie in ASP.NET and html.
I want to upload a file, so I have a model with a HttpPostedFileBase field, and a strongly-typed view that gets the model in order to get the value of the file.
My question is, how can I send to the controller the value of the file?
This is my html code, I'd like to send the value of File to Model.File, but placing <%:Model.File:> instead of file1 does not work :(
<label for="file1">File: </label>
<input type="file" name="file1" id="file1" size="40">
P.S.: I've also tried using the asp:FileUpload but I don't what how to send the result to the controller.
EDIT:
Ok, I go for posting my code, thank you very much ZeNo.
Here is the Model:
public class AddProductModel
{
[...]
public HttpPostedFileBase File { get; set; }
}
This is my View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Application.Models.AddProductModel>" %>
<form id="form1" runat="server">
<% using (Html.BeginForm()) { %>
<% Html.EnableClientValidation(); %>
<fieldset>
[...]
<div>
<label for="file1">File: </label>
<input type="file" name="file1" id="<%: Model.File %>" size="40">
<br />
</div>
<br />
<p>
<input type="submit" value="Add!" />
</p>
</fieldset>
<% } %>
</form>
Here is my controller, I use the debugger here and it says that model.File is empty:
[HttpPost]
public ActionResult AddProduct(AddProductModel model)
{
if (model.ProductName != null && model.ProductDescription != null)
objRepository.addToProducts(model);
return RedirectToAction("/AddProduct");
}
Use <%:Model.File %> instead.
put you file control inside a form tag
<form action="/Home/GetFile" id="myform">
<input type="file1" id="file1"/>
</form>
<script type="text/javascript" language="javascript">
var form = $("#myform");
form .submit();
</script>
controller:
[HttpPost]
public ActionResult GetFile(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
}
}
Change your view to:
<form action ="/AddProduct" id="myform">
<% Html.EnableClientValidation(); %>
<fieldset>
<div>
<label for="file1">File: </label>
<input type="file" name="file1" id="<%: Model.File %>" size="40">
<br />
</div>
<br />
<p>
<input type="submit" value="Add!" />
</p>
</fieldset>
</form>
notice I have removed form runat="server".. also there were nested forms..
add this Javascript snippet:
<script type="text/javascript" language="javascript">
var form = $("#myform");
form .submit();
</script>
in the controller make following changes:
[HttpPost]
public ActionResult AddProduct(HttpPostedFileBase file)
{
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
}
return RedirectToAction("/AddProduct");
}

How can I tell which image has been clicked?

<%using (Html.BeginForm("ChangeLanguage", "AppController", FormMethod.Post))
{ %>
<div id="China">
<input id="imageChina" name="btnsubmitLan" type="image" value="CN" alt='China' src="/Content/Image/IconHH/FlatCN.gif" />
</div>
<div id="US">
<input id="ImageUS" name="btnsubmitLan" type="image" value="US" alt='English' src="/Content/Image/IconHH/FlatUS.jpg" />
</div>
<div id="VietNam">
<input id="ImageVN" name="btnsubmitLan" type="image" value="VN" alt='VietNam' src="/Content/Image/IconHH/FlatVN.jpg" />
</div>
<%} %>
In controller :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChangeLanguage(string btnsubmitLan, FormCollection form)
{//chu yeu load o phan template
if (btnsubmitLan != null)
{
switch (btnsubmitLan)
{
case "VN": Session["language"] = "VN"; break;
case "CN":
case "US": Session["language"] = "EN"; break;
}
}
return RedirectToAction("Index");
}
But btnSubmit always null. Why????
I'd be using jQuery and then do an AJAX post to a controller passing in an id of some sort.
<input id="ImageVN" name="btnsubmitLan" type="image" value="VN" alt='VietNam' src="/Content/Image/IconHH/FlatVN.jpg" />
$('input').click( function() {
var id = this.attr("id");
//now do your ajax postback passing in the id.
} );

Resources