using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Csharp_ASPNetCore.Pages.Shared
{
public class ExampleController : Controller
{
public ExampleController()
{
}
[HttpGet]
[Route("/example/")]
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route("/example/")]
public IActionResult Index(string someValue)
{
string buttonClicked = "";
if (HttpContext.Request.Form.ContainsKey("btnOne"))
{
buttonClicked = "btnOne";
int a = 1;
int b = 2;
int c = a + b;
// return View("AAAAAA");
}
else if (HttpContext.Request.Form.ContainsKey("btnTwo"))
{
buttonClicked = "btnTwo";
}
return View("Index");
}
}
}
The last View("Index") command doesn't work, returning this error:
"An unhandled exception occurred while processing the request. InvalidOperationException: The view 'Index' was not found. The following locations were searched: /Views/Example/Index.cshtml /Views/Shared/Index.cs
Following I report the Index.cshtml where there are the buttons (the name of the controller is ExampleController.cs). Thanks!
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div>
<form asp-controller="example" asp-action="Index">
<label>Value:</label>
<input name="someValue" type="text" maxlength="10"/>
<button name="btnOne" type="submit" class="btn btn-default">Click One</button>
<button name="btnTwo" type="submit" class="btn btn-default">Click Two</button>
</form>
</div>
Related
I created a repository and now i want to use a foreach to add multiple items to the page but its giving me a error. My objective is: when there is no items in the page it will show a message but if the page have items will show a different message and the items. The code is the following:
Controller:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Treino1.Models;
namespace Treino1.Controllers
{
public class DespesasController : Controller
{
public IActionResult Index()
{
List<Despesa> despesas = RepositorioDespesas.Despesas;
return View(despesas);
}
[HttpGet]
public IActionResult NovaDespesa()
{
return View();
}
[HttpPost]
public IActionResult NovaDespesa(Despesa despesa)
{
if (ModelState.IsValid)
{
RepositorioDespesas.AddDespesa(despesa);
return View("DespesaConfirmada", despesa);
}
return View();
}
}
}
Repository
using System.Collections.Generic;
namespace Treino1.Models
{
public static class RepositorioDespesas
{
private static List<Despesa> despesas = new List<Despesa>();
public static List<Despesa> Despesas
{
get { return despesas; }
}
public static void AddDespesa (Despesa newDespesa)
{
despesas.Add (newDespesa);
}
}
}
#{
ViewData["Title"] = "Despesa Confirmada";
}
#model List<Treino1.Models.Despesa>
#if (Model.Count== 0)
{
<h1>Sem Despesas...</h1>
}
else
{
<h1>Despesas!</h1>
#foreach (Treino1.Models.Despesa d in Model)
{
<div class="card bg-secondary border-dark">
<div class="card-body">
<b>Nome da Despesa: </b> #d.NomeDespesa
<b>Quantidade: </b> #d.Quantidade
<b>Valor: </b> #d.Valor
<b>Categoria: </b> #d.Categoria
<b>Pago? </b>
#if (d.Pago)
{
#:Sim
}else
{
#:Não
}
</div>
</div>
}
}
<div>
<a asp-action="NovaDespesa">Nova Despesa</a>
</div>
I think the error is something about the Model.Count==0 but i dont know how to solve.
The error is this:
The data model in the DespesaConfirmada strongly typed view is defined as #model List<Treino1.Models.Despesa>, but when it rendered from the public IActionResult NovaDespesa(Despesa despesa) action method the single Treino1.Models.Despesa object is passed. Try to use like below:
public IActionResult NovaDespesa(Despesa despesa)
{
if (ModelState.IsValid)
{
RepositorioDespesas.AddDespesa(despesa);
// Obtain corresponded records from the repository and pass to the view.
return View("DespesaConfirmada", RepositorioDespesas.Despesas());
}
return View();
}
I want to use data annotations in my app and the problem is when I click in submit button and don't fill the required field I don't see any error message and it submits. In the controller, the model.state works fine, but I think I should see the error message.
The model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace ValidationTest.Models
{
public class User
{
[Required(ErrorMessage = "Enter your name.")]
public string Name { get; set; }
public string Lastname { get; set; }
}
}
The View:
#model ValidationTest.Models.User
#{
ViewBag.Title = "Index";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
#using (Html.BeginForm("Record", "Home"))
{
#Html.Label("Name:")
#Html.TextBoxFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
<br />
#Html.Label("Lastname:")
#Html.TextBoxFor(m => m.Lastname)
#Html.ValidationMessageFor(m => m.Lastname)
<input type="submit" value="Record" />
}
</body>
</html>
The controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ValidationTest.Models;
namespace ValidationTest.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Record(User usr)
{
if (ModelState.IsValid)
{
return Content("It Worked!");
}
return RedirectToAction("Index");
}
}
}
In Scripts folder inside the ASP.NET MVC project i have:
bootstrap.js
bootstrap.min.js
jquery-3.2.1.intellisense.js
jquery-3.2.1.js
jquery-3.2.1.min.js
jquery-3.2.1.min.map
jquery-3.2.1.slim.js
jquery-3.2.1.slim.min.js
jquery-3.2.1.slim.min.js
modernizr-2.6.2.js
You will have to add JavaScript script references of jquery.validate.min.js and jquery.validate.unobtrusive.min.js for client side validation to work.
Move return RedirectToAction("Index"); inside if (ModelState.IsValid) condition.
return view(); should be added outside if condition.
I am trying to learn how to use TryUpdateModel but I cannot get it to work, you can find my code below:
Controller Side
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EFW6.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
private WorkFlowContext context = new WorkFlowContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
public string UploadFile(FormCollection form)
{
Files file = new Files();
if (TryUpdateModel(file, form.ToValueProvider()))
{
return "True " + file.filePath;
}
else
{
return "False";
}
}
}
}
View Side
#{
ViewBag.Title = "index";
}
<h2>#Model</h2>
<form method="post" action="Home/UploadFile">
<input type="text" name="filePath">
<input type="submit">
</form>
Model Class
class Files
{
public string filePath;
}
When I return the value of the file path it returns nothing while it returns the value True for as a result for the operation.
the problem is that you I am using field instead of property in the Files Class
You have to change it to be like this
class Files
{
public string FilePath { get; set; }
}
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
I have some questions regarding my MVC learning curve
Goal:
I want to get the txtMHM entered text
after the btnStat is pushed and show the entered text via a label or span or ...
The View Model you should use (simplified):
public class YourViewModel
{
public string TextEntered { get ; set ; }
}
The View:
#model YourViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.TextEntered)
<br />
<input id="btnStat" type="submit" value="MHM" />
}
#Html.LabelFor(m => m.TextEntered)
The Controller Action method:
[HttpPost]
public ActionResult ChangeLabelText(YourViewModel yourViewModel)
{
return View(yourViewModel);
}
Your Altered Code
index.cshtml
#model MVCTest1.Models.EnteredTextModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.TextEntered)
<br />
<input id="btnStat" type="submit" value="MHM" />
}
#Html.LabelFor(m => m.TextEntered)
The Model
namespace MVCTest1.Models
{
public class EnteredTextModel
{
public string TextEntered { get; set; }
}
}
The HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTest1.Models ;
namespace MVCTest1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
[HttpPost]
public ActionResult Index(EnteredTextModel theModel)
{
return View(theModel);
}
public ActionResult About()
{
return View();
}
}
}
Sypress,
Best practice would be to use a viewmodel for your action. However, at a very simple level, based on exactly what you have above, you could use the viewbag object to pass back the input value. without further ado, the frig, i mean code :):
Controller actions:
[HttpGet]
public ActionResult ChangeLabelText()
{
return View();
}
[HttpPost]
public ActionResult ChangeLabelText(FormCollection formCollection)
{
ViewBag.LastNameEntered = formCollection["txtName"];
return View();
}
View stuff (assumes that the view is named ChangeLabelText.cshtml of course):
#{
ViewBag.Title = "ChangeLabelText";
}
<h2>ChangeLabelText</h2>
<form action="ChangeLabelText" method="post">
<input id="txtMHM" type="text" name="txtName" value="" />
<input id="btnStat" type="submit" value="Post" />
<br />
#Html.Label("Entered Text");
<span id="spnEnteredText">#ViewBag.LastNameEntered </span>
</form>
and the above is called as such http://localhost:xxxx/Home/ChangeLabelText (where xxxx is the port number of your dev server)
I would add that this would NOT be the way that I would approach this to be honest, but is my direct response to your example. go for sharks' example using the viewmodel.
good luck
[EDIT] - I've updated my answer now that I'm at a machine, so the above should work as intended.