Update the value in a textbox with controller - asp.net-mvc

In my ASP MVC web application. I have this controller
namespace Test.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index(UserDetails user)
{
user.UserEmail = "Email one";
return View(user);
}
// Post: Home
[HttpPost]
public ActionResult Index(UserDetails user, string command)
{
user.UserEmail = "Email two";
return View(user);
}
#region Helpers
#endregion
}
}
and this view
#model Test.Models.UserDetails
#{ Layout = null;}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DisplayNameFor(model => model.UserEmail)
#Html.EditorFor(model => model.UserEmail)
<input type="submit" name="Command" value="Search" class="btn btn-default" />
A}
</body>
</html>
When I first run the application it will show “Email one” in the textbox. But when I hit the submit button it will not change the value in the textbox to “Email two”. What I have to change on my code?

Related

Server Error in '/' Application in MVC 5 application

I am currently learning MVC 5 by watching video tutorials. I have created one simple customercontroller with two action methods i.e. (AddCustomer and Submit). Here i have created one simple view for AddCustomer and strongly typed view for Showing customer data. When i start application it shows me the customer data entry screen but when i click on submit button i am getting below error.
Can you please tell me what is the issue in my below code?
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Submit
Here's my Customer Controller Code:-
public class CustomerController : Controller
{
// GET: Customer
public ActionResult AddCustomer()
{
return View();
}
public ActionResult Submit(Customer objcust)
{
objcust.CustomerID = Request.Form["txtcustid"];
objcust.CustomerName = Request.Form["txtcustname"];
return View("ShowCustData", objcust);
}
}
Here's My ShowCustData View:-
#model DataAnnotationsEx.Models.Customer
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowCustData</title>
</head>
<body>
<div>
Customer ID: #Model.CustomerID <br />
Customer Name: #Model.CustomerName
</div>
</body>
</html>
Here's My AddCustomer View:-
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddCustomer</title>
</head>
<body>
<div>
<form action="Submit" method="post">
Customer ID: <input id="Text1" type="text" name="txtcustid" /><br />
Customer Name: <input id="Text1" type="text" name="txtcustname" /><br />
<input id="Submit1" type="submit" value="submit" />
</form>
</div>
</body>
</html>
Here's My Customer Model:-
public class Customer
{
[Required]
[StringLength(7)]
[RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")]
public string CustomerID { get; set; }
[Required]
[StringLength(10)]
public string CustomerName { get; set; }
}
Here's My Route.config:-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Customer", action = "AddCustomer", id = UrlParameter.Optional }
);
}
The problem is your Submit controller action doesn't have [HttpPost] attribute, where your form method defined as POST. You should add the mentioned attribute on corresponding action method:
[HttpPost]
public ActionResult Submit(Customer objcust)
{
objcust.CustomerID = objcust.CustomerID;
objcust.CustomerName = objcust.CustomerName;
return View("ShowCustData", objcust);
}
Note that by default if [HttpPost] attribute not specified, it automatically sets as GET method, hence the action method never be reached by form submit request.
Then, you should replace <form> tag with Html.BeginForm() helper with strongly-typed viewmodel definition like this:
#model Customer
#using (Html.BeginForm("Submit", "Customer", FormMethod.Post))
{
#Html.LabelFor(model => model.CustomerID)
#Html.TextBoxFor(model => model.CustomerID)
#Html.LabelFor(model => model.CustomerName)
#Html.TextBoxFor(model => model.CustomerName)
<input id="Submit1" type="submit" value="submit" />
}
By using strongly-typed viewmodel class, the textboxes are bound automatically to viewmodel properties and be able to retrieve values during form submission.

ASP.NET's HttpPost attributed function doesn't seem to execute after form submission

Good evening,
I'm quite new to ASP.NET and I'm doing my best to learn - but I've stumbled upon an issue I can't resolve - because there's no error.
I have this controller:
public class DatabaseFileController : Controller
{
public static string FilePath;
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Select(List<IFormFile> files)
{
Debug.WriteLine("File Reached");
return RedirectToAction("Index");
}
}
And it's meant to execute when I upload a file using this form:
<form id="database-select-form" asp-controller="DatabaseFile" asp-action="Select" method="post" enctype="multipart/form-data">
<input id="database-select" type="file" name="files"/>
I also have a script written in javascript taken from my previous website that makes form submit after file selection (and it does submit) - but nothing shows in my console or the visual studios debug console.
Edit:
As requested, added script that does the submission:
<script>
function select()
{
document.getElementById('database-select').click();
console.log("Clicked");
}
document.getElementById("database-select").onchange = function()
{
document.getElementById("database-select-form").submit();
console.log("Submitted");
};
This is how easy this process is:
Controller:
public class HomeController : Controller
{
[HttpPost]
public ActionResult Upload(string SubmitButton, HttpPostedFileBase file)
{
if (SubmitButton == "Cancel")
{
//redirect to a cancel page
//return RedirectToAction("Index", "Home");
}
//put a breakpoint in this metho to interogate file,
//the file you are going to save to db or do something with
return View();
}
public ActionResult Tut115()
{
return View();
}
View Named Tut115.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut115</title>
</head>
<body>
<div>
#using (Html.BeginForm("Upload",
"Home",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file" /><br>
<input type="submit" name="SubmitButton" value="Cancel" />
<input type="submit" name="SubmitButton" value="Upload" />
}
</div>
</body>
</html>

How to show entered order no and selected product name and id

i am new in mvc. so could not figure out what to add in code to show entered order no and selected product name and id.
here is full code and dotnetfiddle url https://dotnetfiddle.net/6vn2GO
Model code
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class OrderViewModel
{
[Display(Name = "Order number")]
public int? OrderNumber { set; get; }
[Display(Name = "Product")]
[Required(ErrorMessage = "Please select a product")]
public int SelectedProductId { set; get;}
public SelectList ProductList { get; set; }
}
public class Product
{
public int ID { set; get; }
public string Name { set; get; }
}
public static class Repository
{
public static IEnumerable<Product> FetchProducts()
{
return new List<Product>()
{
new Product(){ ID = 1, Name = "Ketchup" },
new Product(){ ID = 2, Name = "Mustard" },
new Product(){ ID = 3, Name = "Relish" }
};
}
}
}
Controller code
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
OrderViewModel model = new OrderViewModel();
model.OrderNumber=null;
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Index(OrderViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
// but for testing purposes
ConfigureViewModel(model);
return View(model);
}
private void ConfigureViewModel(OrderViewModel model)
{
IEnumerable<Product> products = Repository.FetchProducts();
model.ProductList = new SelectList(products, "ID", "Name");
}
}
}
View.cshtml code
#model HelloWorldMvcApp.OrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(m => m.OrderNumber)
#Html.TextBoxFor(m => m.OrderNumber, new {#class="form-control"})
#Html.ValidationMessageFor(m => m.OrderNumber)
</div>
<div class="form-group">
#Html.LabelFor(m => m.SelectedProductId)
#Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {#class="form-control"})
#Html.ValidationMessageFor(m => m.SelectedProductId)
</div>
<button type="submit" class="btn btn-success submit">Save</button>
}
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
please tell me what code i need to add in view html to show entered order no and selected product name and id. thanks
You could set the value of your order number on the [HttpPost] Action method and check if it's null on the view side and show/hide stuff accordingly.
Another (probably better) alternative would be to just create a new view and return that when the model state is valid. To get the order number, you'll need to fetch the inserted ID from the database and pass that to the view.
Edit to show some code:
Controller Code:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
OrderViewModel model = new OrderViewModel();
model.OrderNumber=null;
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Index(OrderViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
// but for testing purposes
ConfigureViewModel(model);
// you'll need to figure out how you're generating your
// order numbers
//
model.OrderNumber = 1; // just set this statically for now for POC
return View(model);
}
private void ConfigureViewModel(OrderViewModel model)
{
IEnumerable<Product> products = Repository.FetchProducts();
model.ProductList = new SelectList(products, "ID", "Name");
}
}
}
View Code:
#model HelloWorldMvcApp.OrderViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
#{
if(Model.OrderNumber == null)
{
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(m => m.OrderNumber)
#Html.TextBoxFor(m => m.OrderNumber, new {#class="form-control"})
#Html.ValidationMessageFor(m => m.OrderNumber)
</div>
<div class="form-group">
#Html.LabelFor(m => m.SelectedProductId)
#Html.DropDownListFor(m => m.SelectedProductId, Model.ProductList, "-Please select-", new {#class="form-control"})
#Html.ValidationMessageFor(m => m.SelectedProductId)
</div>
<button type="submit" class="btn btn-success submit">Save</button>
}
</div>
} else {
<div>show your confirmation stuff here</div>
}
}
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
that will reuse the same view, though as I said, I'd recommend using a different view.

mvc calls httppost always

I am creating a login page:
When I go to the login page Login view should be rendered. on submit, http POST should be triggered which should render the home page with the username. My problem is that whatever I do it is the http GET method that is being called on submit. I am new to mvc ans wondering what I am doing wrong. Why is the program on calling http POST method not submit button click
// My login Class(I mean the model looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace a.Models
{
public class Login
{
public string username { get; set; }
public string password { get; set; }
}
}
// Controller looks like this:
namespace b.Controllers
{
public class LoginController : Controller
{
[HttpPost]
public ActionResult Login(Login Ls)
{
return View();
}
[HttpGet]
public ActionResult Login()
{
return View(new Login());
}
}
}
// Login view look like this
#model a.Models.Login
#{
ViewBag.Title = "Login Page";
}
<html>
<head>
<title>Login Here</title>
<link href="#Url.Content("~/Content/cssLogin.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="bg">
<img src="~/Photos/login2.jpg" />
</div>
<form class="form-2">
<p class="float">
#*<label for="login"><i class="icon-user"></i>Username</label>
<input type="text" name="login" placeholder="Username or email">*#
#Html.LabelFor(model => model.username, new { #class = "icon-use" })
#Html.TextBoxFor(model => model.username, new { data_bind = "value: username" })
</p>
<p class="float">
#*<label for="password"><i class="icon-lock"></i>Password</label>
<input type="password" name="password" placeholder="Password" class="showpassword">*#
#Html.LabelFor(model => model.password, new { #class = "icon-lock" })
#Html.PasswordFor(m => m.password, new { data_bind = "value: password", placeholder = "Password" })
</p>
<p class="clearfix">
<input type="submit" value="Log in">
</p>
</form>
</body>
</html>
// Home View looks like this
#model a.Models.Login
#{
ViewBag.Title = "Home";
}
<h2>Home</h2>
<h2>This is University Home page</h2>
#Model.username
You may need to change the code line this:
public ActionResult Login()
{
return View(new Login());
}
And:
[HttpPost]
public ActionResult Login(Login Ls)
{
return View();
}
And nothing else...

When I submit the partial view by either keeping the textbox filled/empty, in both cases full view is loading. How can I call Ajax to post it?

I have Area in MVC3 as mentioned below.
Model
public class AdminModule
{
[Display(Name = "MyName")]
[Required(ErrorMessage = "MyName is missing")]
public String MyName { get; set; }
}
I have Partial View with following code.
#model _1.Areas.Admin.Models.AdminModule
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "myForm" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<p id="getDateTimeString">
</p>
<input type="submit" value="Click here" id="btn" />
}
View
#model _1.Areas.Admin.Models.AdminModule
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage1.cshtml";
}
<h2>
Index</h2>
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript">
</script>
<script type="text/javascript" src="/scripts/jquery.unobtrusive-ajax.js">
</script>
<div id="myForm">
#Html.Partial("_PartialPage1", Model)
</div>
Layout
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
</head>
<body>
<div>
#RenderBody()
</div>
</body>
</html>
Controller Actions
[HttpPost]
public ActionResult Index(AdminModule model)
{
return PartialView(model);
}
[HttpGet]
public ActionResult Index()
{
AdminModule model = new AdminModule();
model.MyName = "My Name";
return View(model);
}
Confusion
When I submit first time.
I get output like below
and form show like this. Question is - Why is index word coming two times?
When I click second time, form appearance remains same and output shows like below.
Question - Why is Jquery coming so many times ?
You could use an Ajax.BeginForm instead of a regular form. But first you should decide which section of your page you want to be updated after the AJAX call.
Let's suppose the following scenario: if the AJAX call is successful you want to update some section of your DOM with some result and if the AJAX fails you want to update the form and display the error message instead.
To implement this you could start by placing the form inside a partial (_MyForm.cshtml):
#model _1.Models.HomeModels
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "myForm" }))
{
#Html.LabelFor(i => i.MyName)
#Html.TextBoxFor(i => i.MyName)
#Html.ValidationMessageFor(i => i.MyName)
<input type="submit" value="Click here" id="btn" />
}
#if (Model.SomeResultProperty != null)
{
<div>#Model.SomeResultProperty</div>
}
and then you could have your main view reference this partial:
#model _1.Models.HomeModels
<div id="myForm">
#Html.Partial("_MyForm", Model)
</div>
The next step is to update your controller action that will handle the AJAX call:
[HttpPost]
public ActionResult Index(HomeModels model)
{
if (ModelState.IsValid)
{
// validation succeeded => we could set the result property
// on the model to be displayed:
model.SomeResultProperty = "this is the result";
}
return PartialView("_MyForm", model);
}
and finally you need to include the jquery.unobtrusive-ajax.js script to your page in order for the Ajax.BeginForm helper to work:
<script type="text/javascript" src="#Url.Content("~/scripts/jquery.unobtrusive-ajax.js")"></script>
Use Ajax.BeginForm instead.
Did you reference validation scripts in your page?

Resources