would you mind to help me and say what I am doing wrong? I cannot spot the error and consequently after clicking the submit button, the HttpPost ActionResult method is not being hit?
Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(testModel model)
{
if (ModelState.IsValid == true)
{
using (testRepository repository = new testRepository())
{
}
}
return View();
}
And the View
#using (Html.BeginForm("Index", "Test", FormMethod.Post, new {autocomplete="off" }))
{
<fieldset>
#Html.LabelFor(m => m.testValue)
#Html.TextBoxFor(m => m.testValue)
<input type="submit" value="Submit" />
</fieldset>
}
Related
I'm trying to create searcher in asp.net. I'm so green about it. I'm trying to create in view and send to controller variable, which has text written in searcher. In that moment, I have smth like that -->
My question is, where and how create and send variable and give her data written in searcher?
Layout
form class="navbar-form navbar-left" role="search">
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Wpisz frazę...">
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
</form>
Controller
public class SearcherController : ApplicationController
{
[HttpGet]
public ActionResult Index(string message)
{
ViewBag.phrase = message;
getCurrentUser();
return View();
}
}
View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
<li>#ViewBag.message</li>
</ul>
You're missing a key part of MVC -> the Model.
Let's create one first:
public class SearchModel
{
public string Criteria { get; set; }
}
Then let's update your "Layout" view (don't know why you had a form in a form?):
#model SearchModel
#using (Html.BeginForm("Index", "Searcher", FormMethod.Post, new { phrase = "abc" }))
{
<div class="form-group">
#Html.EditorFor(m => m.Criteria)
</div>
<button type="submit" class="btn btn-default">#Html.ActionLink("Szukaj", "Index", "Searcher")</button>
}
Then your action that serves that view:
[HttpGet]
public ActionResult Index()
{
return View(new SearchModel());
}
Then your post method would be:
[HttpPost]
public ActionResult Index(SearchModel model)
{
ViewBag.phrase = model.Criteria;
getCurrentUser();
return View();
}
I keep getting this error:
The model item passed into the dictionary is of type 'OutsourcedTicketPlatform.UI.ViewModels.Home.AccountSearchViewModel', but this dictionary requires a model item of type 'OutsourcedTicketPlatform.UI.ViewModels.Home.AccountDetailsViewModel'.
Home controller:
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult SearchResults(AccountSearchViewModel model)
{
if (ModelState.IsValid)
{
AccountDetailsViewModel accountDetails = new AccountDetailsViewModel(model.CustomerReferenceNumber);
return View(accountDetails);
}
return View("Index");
}
[Authorize]
public ActionResult MobileResults(AccountDetailsViewModel model)
{
if (ModelState.IsValid)
{
AccountDetailsViewModel accountDetails = new AccountDetailsViewModel(model.CustomerReferenceNumber);
return View(accountDetails);
}
return View("Index");
}
}
MobileIssueReporterview:
#model OutsourcedTicketPlatform.UI.ViewModels.Home.AccountDetailsViewModel
#{
ViewBag.Title = "Mobile Issue Reporter";
}
<h2>Mobile Issue Reporter</h2>
<p>Hi (CustomerName) are you phoning today to log the mobile device as lost or stolen?</p>
<p>"Please Confirm your mobile number"</p>
<p>#Html.TextBox("mobileNumber")</p>
Search results view (this navigates to the mobile issue reporter)
#model OutsourcedTicketPlatform.UI.ViewModels.Home.AccountDetailsViewModel
#{
ViewBag.Title = "Key Account Management";
}
<fieldset>
<legend>#ViewBag.Title</legend>
<p>Please provide the account name:</p>
#foreach (var item in Model.AccountContacts)
{
#Html.RadioButton("AccountContact", item) #item
}
<input id="ContactNotListedButton" type="button" value="Contact name not on list" />
<p>Please provide the first line of the billing address:</p>
#Html.RadioButton("BillingAddressFirstLine", Model.BillingAddressFirstLine, false) #Model.BillingAddressFirstLine
<input id="NoMatchingDetailsButton" type="button" value="No Matching Details" />
#* 1 = Unicom, 2 = Titan *#
#if (Model.AccountType == 1 || Model.AccountType == 2)
{
<input id="NextButton" type="button" value="Next" />
}
#if (Model.AccountType == 1 && Model.IsKeyAccount && Model.HasActiveMobileContracts)
{
using (Html.BeginForm("MobileResults", "Home", FormMethod.Post))
{
#Html.Hidden("CustomerReferenceNumber","123456")
#Html.Hidden("customerName", "John Smith")
#Html.Hidden("mobileNumber", "123456789")
<input type="submit" value="Mobile Lost or Stolen?" />
}
}
</fieldset>
The error is happening when I click on the Mobile Lost or Stolen? button
It Seems You are passing populated values with the model AccountSearchViewModel but that view is expecting data from AccountDetailsViewModel chek with AccountDetailsViewModel model it will work fine.
I am using ASP.net MVC 4 with the Razor engine.
I have a page (Index.cshtml) and a controller (HomeController.cs)
I am trying to hook up my submit button to an Action Result in my controller - however i can't seem to get it to fire.
My HTML :
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
{
<div class="main-Background">
******lots of other html here*******
<button type="submit" id="btnSave">Save</button>
</div>
}
My Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
}
At the moment i havn't implemented a model to pass the values through to the controller, i just wanted to see if i could get the ActionResult SubmitForm to fire.
I have tried #using (Html.BeginForm()) with no parameters, i have also tried including [HttpPost] above my ActionResult, without any luck.
Edit i have also tried using <input type="submit" id="btnSave">Save</input> instead of a button.
Not sure where i am going wrong
It turns out that jQuery was stopping the ActionResult from being hit.
I had a button click event which was "eating up" the ActionResult functionality. I solved this by calling my ActionResult using Ajax.
You dont need to use "-Controller" suffix. Use just Home instead of HomeController, MVC will convert it for you.
Use
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
instead of
#using (Html.BeginForm("SubmitForm", "HomeController", FormMethod.Post, new { id = "submitForm" }))
Full codes
view
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
{
<div class="main-Background">
******lots of other html here*******
<input type="submit" id="btnSave">Save</input>
</div>
}
And controller
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
View:
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
{
<div class="main-Background">
******lots of other html here*******
<button type="submit" id="btnSave">Save</button>
</div>
}
Controller:
[HttpPost]
public ActionResult SubmitForm()
{
return View();
}
May be the problem is occurred because of other HTML inside your div so check it out. Otherwise it works perfectly.
You need to add Html.BeginForm with the parameters. Here is an example:
ActionName – Name of the Action. In this case the name is Create.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
http://localhost:60386//Home/Create
#using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
#Html.EditorFor(model => model.FirstName)
<input type="submit" value="Create"/>
}
HomeController.cs:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(person);
}
TL;DR
I had [Required] data attributes on my view model preventing the submit from working when the form wasn't filled.
I had two submit buttons in my MVC code, one for Submit, the other for Cancel.
Both buttons were firing correctly on data entry, but neither when nothing was entered.
It took me a bit to realize that my view model had [Required] field validations in place!
View:
#using (Html.BeginForm(actionName: "Index", controllerName: "User", method: FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(m => m.PhoneNumber)
...
<input type="submit" name="submitAction" value="Verify" />
<input type="submit" name="submitAction" value="Cancel" />
}
ViewModel:
public class UserViewModel
{
[Required]
[MaxLength(10)]
public string PhoneNumber { get; set; }
[Required]
...
}
Controller Method:
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Index(UserViewModel viewModel, string submitAction)
{
switch(submitAction)
{
case "Verify": ...
case "Cancel": ...
}
}
Change this #using (Html.BeginForm("SubmitForm", "HomeController", FormMethod.Post, new { id = "submitForm" }))
to
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm" }))
Explanation : No need to suffix Controller anywhere, it being accepted by default
and in the Controller
[HttpPost]
public ActionResult SubmitForm(string id)
{
return View();
}
Explanation : as the Form Method given by you is Post so need to include [HttpPost] before the Action and the parameter you were passing was missing in the action method
I have created the following view, with having file upload and submit button.
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
I have also created the action method in Controller but it gives the null at the "uploadFile"
[HttpPost)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
Can u try Name with same as uploadFile
In your Page:
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="uploadFile" name="uploadFile" type="file" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
As per #Willian Duarte comment : [HttpPost]
In your Code behind:
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile) // OR IEnumerable<HttpPostedFileBase> uploadFile
{
//For checking purpose
HttpPostedFileBase File = Request.Files["uploadFile"];
if (File != null)
{
//If this is True, then its Working.,
}
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
See here Same question like yours.,
Code project Article about the File upload.,
Try to use (on controller):
var file = System.Web.HttpContext.Current.Request.Files[0];
create a model and bind it to your view that controller will also expect:
Controller:
//Model (for instance I've created it inside controller, you can place it in model
public class uploadFile
{
public HttpPostedFileBase file{ get; set; }
}
//Action
public ActionResult Index(uploadFile uploadFile)
{
if (uploadFile.file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.file.FileName));
uploadFile.file.SaveAs(filePath);
}
return View();
}
View
#model sampleMVCApp.Controllers.HomeController.uploadFile
#using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.file, new { type = "file"});
<input type="submit" value="Upload File" id="btnSubmit" />
}
Tested Solution!
HTH :)
Use the following in the controller:
var file = System.Web.HttpContext.Current.Request.Files[0];
Use HttpPost instead of [AcceptVerbs(HttpVerbs.Post)]
I have got the two buttons in the same view one is working with the data to show in a label in another view and I have written the function for the button2 (adding another value), when I click on the button2 its not showing the data in view ..... rather it's giving error like this ... http:404 Resource not found error
and this is the view
#model MvcSampleApplication.Models.products
#{
ViewBag.Title = "Valuesadd";
}
<h2>Valuesadd</h2>
#using (Html.BeginForm("SubmitValue","EnterValue",FormMethod.Post))
{
<div>
<fieldset>
<legend>Enter Textbox Value</legend>
<div class ="editor-label">
#Html.LabelFor(m => m.EnteredValue)
</div>
<div class="editor-field">
#Html.TextBoxFor(m=>m.EnteredValue)
</div>
<p>
<input type="submit" value="Submit1" />
</p>
</fieldset>
</div>
}
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
<p>
<input type="submit" value="Submit2" />
</p>
}
and this is the controller for
namespace MvcSampleApplication.Controllers
{
public class EnterValueController : Controller
{
[HttpPost]
public ActionResult SubmitValue(MvcSampleApplication.Models.products model)
{
TempData["logindata"] = model.EnteredValue;
return RedirectToAction("submittedvalues" , "SubmitValue2");
// how can we redirect to another view when the button is clicked in one view
}
public ActionResult submittedvalues()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = data;
return View(model);
}
// action for second button click
public ActionResult submittedvalues2()
{
var model = new MvcSampleApplication.Models.category();
string data = TempData["logindata"] != null ? TempData["logindata"].ToString() : "";
model.lablvalue = "HIIII"+data;
return View(model);
}
}
}
would you pls suggest any idea ..
Many thanks...
Your form action and action in the controller are not named the same. Also you don't have a HttpPostfor it
#using (Html.BeginForm("SubmitValue2","EnterValue",FormMethod.Post))
{
}
//add this
[HttpPost]
public ActionResult submittedvalues2()
{
var model = SOMETHING;
return View("submittedvalues", model);
}
or
[HttpPost]
public ActionResult submittedvalues2()
{
//Do your post actions and redirect to action
return RedirectToAction("submittedvalues");
}
SubmitValue2 in the form should be submittedvalues2, and add a HttpPost attribute on it