I have:
GuestResponseRepository, IRepository -> Interface, HomeController -> Controlle, Thanks -> View
The GuestReresponseRepository has a list with responses in it. When I add a response via a form the response is added to the list. When you try to add a response for the second time with the same values the AddReponse method returns false. I want to use the bool in my view to display a different text. How can I do this? Below my code
GuestResponseRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PartyInvites.Abstract;
namespace PartyInvites.Models
{
public class GuestResponseRepository : IRepository
{
private static List<GuestResponse> responses = new List<GuestResponse>();
IEnumerable<GuestResponse> IRepository.GetAllResponses()
{
return responses;
}
bool IRepository.AddResponse(GuestResponse response)
{
if (responses.Any(x => x.Email == response.Email)) //here
{
if (responses.Any(x => x.WillAttend == response.WillAttend)) //here
{
return false;
}
var attend = responses.First(x => x.Email == response.Email && x.WillAttend != response.WillAttend);
attend.WillAttend = response.WillAttend;
return true;
}
responses.Add(response);
return true;
}
}
}
IRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PartyInvites.Models;
namespace PartyInvites.Abstract
{
public interface IRepository
{
IEnumerable<GuestResponse> GetAllResponses();
bool AddResponse(GuestResponse response);
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartyInvites.Models;
using PartyInvites.Abstract;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
private IRepository repository;
public HomeController(IRepository iRepository)
{
this.repository = iRepository;
}
public ViewResult Index() {
return View(repository.GetAllResponses());
}
public ViewResult PartyPeople()
{
return View(repository.GetAllResponses());
}
[HttpGet]
public ViewResult RsvpForm() {
return View();
}
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
if (ModelState.IsValid) {
repository.AddResponse(guestResponse);
return View("Thanks", guestResponse);
}
else
{
// there is a validation error
return View();
}
}
}
}
view
#model PartyInvites.Models.GuestResponse
#{
ViewBag.Title = "Thanks";
}
<div class="text-center">
<h1>Thank you, #Model.Name!</h1>
<div class="lead">
#if (Model.WillAttend == true) {
#:It's great that you're coming. The drinks are already in the fridge!
} else {
#:Sorry to hear that you can't make it, but thanks for letting us know.
}
#if (bool from Addresponse is false) {
#:<p>You already submitted this response. Are you sure this is right?</p>
}
</div>
Link naar pp
</div>
Capture the return from AddResponses in a boolean variable and set a custom property in the ViewBag object
bool result = repository.AddResponse(guestResponse);
ViewBag.Response = result;
return View("Thanks", guestResponse);
Now in the Thanks view you can use this property to decide which text to write
#model PartyInvites.Models.GuestResponse
#{
ViewBag.Title = "Thanks";
bool response = (ViewBag.Response != null ? Convert.ToBoolean(ViewBag.Response) : false);
}
.....
#if (!response) {
#:<p>You already submitted this response. Are you sure this is right?</p>
}
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();
}
This is my roles under homecontroller file there are 3 user as below how do i add functionality to manager so he can view /edit or delete
what all files ill need to edit i tried youtube and stuff but didnt find a clear picture
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CustomRoleProvider.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[Authorize(Roles="User")]
public ActionResult UserArea()
{
return View();
}
[Authorize(Roles ="Admin")]
public ActionResult AdminArea()
{
return View();
}
[Authorize(Roles = "Manager")]
public ActionResult ManagerArea()
{
return View();
}
}
}
I have an ASP.NET Core MVC application that has references to two Razor Class Libraries. In each RCL, there is a Model class with the same name (Call it GeneralModel). When the application is ran the following error occurs:
InvalidOperationException: The model item passed into the
ViewDataDictionary is of type 'Namespace1.Models.GeneralModel', but this
ViewDataDictionary instance requires a model item of type
'Namespace2.Models.GeneralModel'.
If I rename one of the Models in one of the RCLs to be unique, the error does not occur and the App preforms as expected.
I produced a bare bones App along with two bare bones RCLs to make sure it wasn't something in our real Solution. The error re-occurred.
Here's the code:
RCL 1 Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestRCL1.Models;
namespace TestRCL1.Controllers
{
public class TestRCL1Controller : Controller
{
public IActionResult Index()
{
try
{
GeneralModel generalModel = new GeneralModel();
generalModel.fooBar = "fooBar from RCL1";
return PartialView("_GeneralView", generalModel);
}
catch (Exception ex)
{
string s = ex.ToString();
return NotFound();
}
}
}
}
RCL 2 Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestRCL2.Models;
namespace TestRCL2.Controllers
{
public class TestRCL2Controller : Controller
{
public IActionResult Index()
{
try
{
GeneralModel generalModel = new GeneralModel();
generalModel.fooBar = "fooBar from RCL2";
return PartialView("_GeneralView", generalModel);
}
catch (Exception ex)
{
string s = ex.ToString();
return NotFound();
}
}
}
}
RCL 1 Model:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestRCL1.Models
{
public class GeneralModel
{
public string fooBar { get; set; }
}
}
RCL 2 Model:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestRCL2.Models
{
public class GeneralModel
{
public string fooBar { get; set; }
}
}
RCL 1 View:
#model TestRCL1.Models.GeneralModel
<div>#Model.fooBar</div>
RCL 2 View:
#model TestRCL2.Models.GeneralModel
<div>#Model.fooBar</div>
Main App's Home Controller:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TestRCLApp.Models;
namespace TestRCLApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
Main App's Index.cshtml:
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<button id="loadRCL1Content" type="button">Load RCL1 Content</button>
<button id="loadRCL2Content" type="button">Load RCL2 Content</button>
</div>
<script>
$('#loadRCL1Content').click(function (e) {
$.ajax({
url: '/TestRCL1/Index',
type: 'POST'
})
.fail(function (req, status, error) {
alert(error);
})
.done(function (responseData, status, responseObj) {
$('#partialPlaceHolder').html(responseData);
});
});
$('#loadRCL2Content').click(function (e) {
$.ajax({
url: '/TestRCL2/Index',
type: 'POST'
})
.fail(function (req, status, error) {
alert(error);
})
.done(function (responseData, status, responseObj) {
$('#partialPlaceHolder').html(responseData);
});
});
</script>
Test App's Solution Explorer Screen Shot
Has anyone else run into this issue? Do I just need to keep all the Model's uniquely named through out my RCLs or is there a better solution? Thanks in advance!
Your error says it all.
Just because they look the same, doesn't mean they are the same. The compiler is smarter than that and will treat 2 separate classes as 2 separate classes.
Use the same model. or use an interface if you need
I made a web API from Entity framework and then I tried to make a DELETE call so I can delete stuff from my jquery datatable through AJAX. I'm getting an error that DELETE localhost/ api is not found. Here is my code.
#section scripts{
<script>
$(document).ready( function () {
var table = $('#myTable').DataTable();
$("#myTable .js-delete").on("click", function () {
var button = $(this);
//bootbox.confirm("Do you want to delete this movie?", function (result) {
//if (result) {
$.ajax({
url: "/api/FriendApi/" + button.attr("data-friend-id"),
method: "DELETE",
success: function () {
table.row(button.parents("tr")).remove().draw();
}
});
//}
//});
})
} );
</script>
}
This is my web api
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace WebApplication2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
ApiController
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
public class FriendApiController : ApiController
{
private FriendContext db = new FriendContext();
// GET: api/FriendApi
public IQueryable<FriendModel> Getfriends()
{
return db.friends;
}
// GET: api/FriendApi/5
[ResponseType(typeof(FriendModel))]
public IHttpActionResult GetFriendModel(int id)
{
FriendModel friendModel = db.friends.Find(id);
if (friendModel == null)
{
return NotFound();
}
return Ok(friendModel);
}
// PUT: api/FriendApi/5
[ResponseType(typeof(void))]
public IHttpActionResult PutFriendModel(int id, FriendModel friendModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != friendModel.Id)
{
return BadRequest();
}
db.Entry(friendModel).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!FriendModelExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/FriendApi
[ResponseType(typeof(FriendModel))]
public IHttpActionResult PostFriendModel(FriendModel friendModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.friends.Add(friendModel);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = friendModel.Id }, friendModel);
}
// DELETE: api/FriendApi/5
[ResponseType(typeof(FriendModel))]
[Route("FriendModel/{id}")]
public IHttpActionResult DeleteFriendModel(int id)
{
FriendModel friendModel = db.friends.Find(id);
if (friendModel == null)
{
return NotFound();
}
db.friends.Remove(friendModel);
db.SaveChanges();
return Ok(friendModel);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool FriendModelExists(int id)
{
return db.friends.Count(e => e.Id == id) > 0;
}
}
}
Basically this is my WebApi and the Api I made myself (in this case I used Entity's framework Api). I wrote the same code like a week ago and it worked but now it doesn't work. I have no clue why.
Your C# code has:
[Route("FriendModel/{id}")]
But your script is requesting:
DELETE /api/FriendApi/{id}
Spot the difference!
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; }
}