My form's ActionResult method is not properly being fired after the submit button is clicked. I've spent a few hours searching on the issue and can't find out why the ActionResult is not being fired.
Index.cshtml
#model Azure.Models.UserModel
<form method="post">
<div class="text-center">
<br/>
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
{
#: Name: #Html.TextBoxFor(m => m.Name) <br /> <br />
#: Note: #Html.TextBoxFor(m => m.Note) <br /> <br />
<button type="submit" id="btnSubmit" class="btn">Submit</button>
}
</div>
</form>
HomeController.cs
public class HomeController : Controller
{
[HttpPost]
public ActionResult SubmitForm(UserModel model)
{
String name = model.Name;
String note = model.Note;
//Insert into database
return View();
}
}
I know this is probably very trivial but I can't find anything explaining why the event isn't being fired.
You are nesting a form within a form: the construct
#using(Html.BeginForm()) { }
outputs both an opening and closing tag for a form element.
If you remove the form tags wrapping your using statement, you should find it works.
Related
How can do I set the default value to a hidden input box in html page using ASP.NET MVC.
Seems you are trying to set hidden value on asp.net MVC. You could
try below way.
Model:
public class HiddenValueModel
{
public int HiddenValueId { get; set; }
public String HiddenValueName{ get; set; }
}
Load Default View From Controller:
public IActionResult HiddenValueExample()
{
return View();
}
View:
#model MVCApps.Models.HiddenValueModel
#{ ViewBag.Title = " "; }
<h2>Hidden Value Example </h2>
<hr />
#using (Html.BeginForm("HiddenValueExamplePost", "controllerName"))
{
<table class="table table-sm table-bordered table-striped">
<tr><th>HiddenValueName </th><td id="HiddenValueName"> #Html.TextBoxFor(r => Model.HiddenValueName, new { #class = "form-control" })</td></tr>
<tr><th>HiddenValue Id Which Is Hidden</th><td id="HiddenValueId"><input type="hidden" id="HiddenValueId" name="HiddenValueId" value="01052022" /></tr>
</table>
<input id="Button" type="submit" value="Save" class="btn btn-primary" style="margin-left:1091px" />
}
Note: Here you could see HiddenValueId we have set the value into the feild and keep that hidden. But when you would submitted the
value to the controller it would be there. Additionally, if you want to bind the hidden value from your backend you can use this way #Html.HiddenFor(m => m.HiddenValueId, new { #value = Model.HiddenValueId} ). You could also have a
look more details on official document here
Submit Value To Controller:
[HttpPost]
public IActionResult HiddenValueExamplePost(HiddenValueModel modelWithHiddenValue)
{
return View();
}
Output:
When Bind From Controller:
public IActionResult HiddenValueExample()
{
var hiddenExamVal = new HiddenValueModel();
hiddenExamVal.HiddenValueId = 10101;
hiddenExamVal.HiddenValueName = "Test Hidden Value";
return View(hiddenExamVal);
}
Bind From Controller and submit that value again to controller:
In this case update the view like this :
#model MVCApps.Models.HiddenValueModel
#{ ViewBag.Title = " "; }
<h2>Hidden Value Example </h2>
<hr />
#using (Html.BeginForm("HiddenValueExamplePost", "StackOverFlow"))
{
<table class="table table-sm table-bordered table-striped">
<tr><th>HiddenValueName </th><td id="HiddenValueName"> #Html.TextBoxFor(r => Model.HiddenValueName, new { #class = "form-control" })</td></tr>
<tr><th>HiddenValue Id Which Is Hidden</th><td id="HiddenValueId">#Html.HiddenFor(m => m.HiddenValueId, new { #value = Model.HiddenValueId} )<br /></tr>
</table>
<input id="Button" type="submit" value="Save" class="btn btn-primary" style="margin-left:1091px" />
}
<br />
Output Using Backend Binding:
Hope it would guided you accordingly.
Creating a Hidden Field in ASP .NET MVC
Studentmodel:
public class Student{
public int StudentId { get; set; }
public string StudentName { get; set; }}
HiddenFor() in Razor View:
#model Student
#Html.HiddenFor(m => m.StudentId)
Html Result :
<input data-val="true"
data-val-number="The field StudentId must be a number."
data-val-required="The StudentId field is required."
id="StudentId"
name="StudentId"
type="hidden"
value="" />
Html.Hidden() :
#model Student
#Html.Hidden("StudentId")
Html Result :
<input id="StudentId" name="StudentId" type="hidden" value="1" />
Basic Helper (#Html.Hidden())
If you want a Hidden Field with its value set you can try this:
#Html.Hidden("Jeremy", "Thompson")
The Hidden Field's name will be "Jeremy", and the value of the Hidden Field will be "Thompson".
Strongly Typed Helper (#Html.HiddenFor()) / Model Binding
The strongly typed helper contains 2 parameters:
Hidden Field name which is the name of a Model Property.
Value of Hidden Field (if we want to set the value from the view).
Declaration of Hidden Field using strongly typed helper:
#Html.HiddenFor(m => m.StudentID, new { Value = "1" })
Ref
I'm developing asp.net core mvc web application. In my controller, there're two actions named 'Index' and 'Index2'.
When I submit form to 'Index2', it will return View("Index", model). But the view doesn't render correctly.
For example, if I input 'Steven' in the TextBox and submit to 'Index2' action, the Name property should be 'Name999'. The Textbox on the HTML should be show 'Name999', but actually, it still show 'Steven'.
The code sample:
#model WebApplication2.Controllers.Test
<form method="post" action="/home/Index2">
<div class="form-group">
<input type="text" asp-for="Name"/>
</div>
<div class="form-group">
<button type="submit">Add</button>
</div>
</form>
public IActionResult Index(Test test)
{
return View(test);
}
[HttpPost]
public IActionResult Index2(Test test)
{
test.Name = "Name999";
return View("Index",test);
}
public class Test
{
public string Name { get; set; }
}
you are submitting your form to index, not to index2
try this
view Index
#model WebApplication2.Controllers.Test
<form asp-action="Index2" method="post">
<div class="form-group">
<input type="text" asp-for="Name"/>
</div>
<div class="form-group">
<button type="submit">Add</button>
</div>
</form>
and try to refresh model state since you are doing a post back
ModelState.Clear();
test.Name = "Name999";
or change the view control
<input type="text" asp-for="Name" value="#Model.Name"/>
But when it is the same controller I am personaly usually using
return Index(test);
I can reproduce same issue, and I find that it seems to get value from ModelState prior to Model, which cause above issue.
To fix it, we can try to clear it, like below.
public IActionResult Index( )
{
return View();
}
[HttpPost]
public IActionResult Index2(Test test)
{
ModelState.Clear();
test.Name = "Name999";
return View("Index", test);
}
#model WebApplication99.Models.Test
<form method="post" action="/test/Index2">
<div class="form-group">
<input type="text" asp-for="Name" />
</div>
<div class="form-group">
<button type="submit">Add</button>
</div>
</form>
Note: the valus of ModelState
Result:
I have problem with passing values by POST in ASP.NET MVC 4
This is my action in User controller:
[HttpPost]
public string Show(int? uid, string uname)
{
return uname + uid.ToString();
}
And this is how I tried to pass values in view:
#using (Html.BeginForm("Show", "User"))
{
Html.Hidden("uid", Model.Id);
Html.Hidden("uname", Model.UserName);
<input type="submit" value="+"/>
}
html:
<form action="/User/Show" method="post"> <input type="submit" value="+"/> </form>
and:
#using(Html.BeginForm("Show", "User", FormMethod.Post, new { uid = 1, uname = "user1" }))
{
<input type="submit" value="+"/>
}
html:
<form action="/User/Show" method="post" uid="1" uname="user1"> <input type="submit" value="+"/></form>
In both ways Show action receives null instead real values.
Your HtmlHelpers are not being rendered. Use Razor syntax.
#using (Html.BeginForm("Show", "User"))
{
#Html.Hidden("uid", Model.Id);
#Html.Hidden("uname", Model.UserName);
<input type="submit" value="+"/>
}
Explanation:
Calling Html.Hidden (or Html.[anything]) is a method and usually returns an IHtmlString. Without using # infront, the engine doesn't know that you're trying to output the returned string. It just thinks you're calling a method.
This is not a good approach for an action that receives data. This approach can offer many security breaches, like data injection., essentially lots of fields.
The right thing is create a Model (or a ViewModel, if you don't want to persist the data) to make the correct guidance between View and Controller:
ViewModel:
public class MyViewModel {
public int? uid { get; set; }
public string uname { get; set; }
}
View:
#model MyProject.ViewModels.MyViewModel
#using (Html.BeginForm("Show", "User"))
{
Html.HiddenFor(model => model.uid);
Html.HiddenFor(model => model.uname);
<input type="submit" value="+"/>
}
Controller:
public ActionResult Show(int modelId) {
var model = context.Model.SingleOrDefault(m => m.ModelId == modelId);
var viewModel = new MyViewModel();
viewModel.uid = model.Id;
viewModel.uname = model.UserName;
return View(viewModel);
}
[HttpPost]
public string Show(MyViewModel viewModel)
{
return viewMode.uname + viewModel.uid.ToString();
}
You're not actually creating hidden fields in your form. You need the # in front of you Hidden helper, and drop the semi-colon at the end.
#using (Html.BeginForm("Show", "User"))
{
#Html.Hidden("uid", Model.Id)
#Html.Hidden("uname", Model.UserName)
<input type="submit" value="+"/>
}
The reason your hard-coded test didn't work is that your HTML wasn't correct. You can't just put the values you want to post on the <form> element, you need to have them as hidden fields in the form.
<form action="/User/Show" method="post">
<input type="hidden" name="uid" value="1" />
<input type="hidden" name="uname" value="user1">
<input type="submit" value="+"/>
</form>
It would be better if you could use a view model.
public class MyViewModel
{
public int? Id {get;set;}
public string UserName {get;set;}
}
public ActionResult Show()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Show(MyViewModel model)
{
return Content(string.format("{0} - {1}", model.Id, model.UserName));
}
(Coded in notepad so untested, but should work.)
I have an Action result method that is supposed to add data into a database when a button is clicked. Although, when I click on the button to add the data using the AddDetails Action method I get the following Error:
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: /home/AddDetails
Controller:
namespace //not included
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Details()
{
return View();
}
[HttpPost]
public ActionResult AddDetails(Customer customer)
{
if (ModelState.IsValid)
{
var db = new CustomerContext();
db.Customers.Add(new Customer
{
ItemName = customer.ItemName,
Price = customer.Price
});
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
}
}
View:
#{
ViewBag.Title = "Details";
}
<h2>Add Items</h2>
<div class="container">
<form class="form-signin" role="form">
<h2>Please type in Item Name and price paid</h2>
<input type="text" class="form-control" placeholder="Name" required autofocus />
<input type="number" pattern="[0-9]+([\.|,][0-9]+)?" step="0.01" min="0" class="form-control" placeholder="Price" required autofocus />
<input type="button" class="btn btn-lg btn-primary btn-block" value="Add" onclick="location.href='#Url.Action("AddDetails", "home")'" />
</form>
</div>
You're posting to /Customers/Details but your action is /Customers/AddDetails. You can tell your form to specifically post to /Customers/AddDetails or you can rename your AddDetails action to Details. It's fine to have both a GET and POST action called Details. When you issue a post request, the action with the HttpPost attribute will be hit. When you issue a get request, the action with no attribute or a HttpGet attribute will be hit.
If you want to keep the name 'AddDetails', your form should look like this (I'm using Razor instead of plain HTML):
#using (Html.BeginForm("AddDetails", "Home", FormMethod.Post) {
<h2>Please type in Item Name and price paid</h2>
<input type="text" class="form-control" placeholder="Name" required autofocus />
<input type="number" pattern="[0-9]+([\.|,][0-9]+)?" step="0.01" min="0" class="form-control" placeholder="Price" required autofocus />
<input type="submit" class="btn btn-lg btn-primary btn-block" value="Add" />
}
I guess, I don't type fast enough... As Neil mentioned, use the Html Helper, though I recommend using named parameters so that you don't confuse which is the Action and Controller:
#using (Html.BeginForm(
actionName: "AddDetails",
controllerName: "Customer",
method: FormMethod.Post,
htmlAttributes: new { #class = "myclass" }))
Also, to help keep the routes correct (and not need to rely on "magic strings"), I highly recommend using T4MVC. Then your form will look like this:
#using (Html.BeginForm(MVC.Customer.AddDetails(), ...)
And the Razor view will not even render if the Action does not exist. It is also easier writing the form because Intellisense will help you find the Controller and Action you want.
Make These changes in your code.
namespace //not included
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult AddDetails()
{
Customer newCustomer = new Customer();
return View(newCustomer);
//right click this action and choose addview and use strongly typed
//view by choosing Customer class
}
[HttpPost]
public ActionResult AddDetails(Customer customer)
{
//whatever you want here
}
}
}
You will get a view with all the syntax for form and input textBoxes. Just few minor additions to meet your UI requirement will be needed.
Feel free to ask more doubts if any.
You need to give Action name in Html.BeginForm like this #using (Html.BeginForm("AddDetails", "Home", FormMethod.Post)
Or
change you controller action name to Details instead of AddDetails
I have a MVC project im currently working on and i have a check box in one of my views. When i change the check box it never passes the correct value to my modal?
View CheckboxFor:
#model OBASA.Models.EmployeeModal
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Active)
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active)
</div>
<p>
<input type="submit" name="Sub" value="Save" />
</p>
</fieldset>
}
Modal:
public class EmployeeModal
{
public bool Active { get; set; }
}
In run time when i check or un check the check box it never passes the value, its always false.
Please can someone tell me how to bind this correctly for MVC.
The code you've posted is correct, though you have not posted your controller code. It needs to look something like this:
public ActionResult Junk()
{
return View();
}
[HttpPost]
public ActionResult Junk(EmployeeModal model)
{
bool bActive = model.Active;
return View(model);
}