Can't receive the value of selectec item from Radio Button - asp.net

So, I'm trying to do a online pool but I cant receive the value of selected item...
If someone can help me here is my Controller:
public async Task<IActionResult> Vote(int id, string text)
{
using (var poolDbContext = new PoolContext())
{
var Voted = new Vote();
var queq = new Answer { Id = id, Text = text };
// var Question = await poolDbContext.Questions.Include(s => s.Answers).AsNoTracking().SingleOrDefaultAsync(m => m.Id == id);
var Question = await poolDbContext.Questions.Include(A => A.Answers).AsNoTracking().SingleOrDefaultAsync(r => r.Id == r.Id);
if (Question == null)
{
return NotFound();
}
return View(Question);
}
}
[HttpPost, ActionName("Vote")]
[ValidateAntiForgeryToken]
public ActionResult VotePost(Question question)
{
try
{
if (ModelState.IsValid)
{
using (var poolDbContext = new PoolContext())
{
var id = question.Id.ToString();
var qId = question.Id;
var selectedAnswer = question.SelectedAnswer;
poolDbContext.SaveChanges();
// Save the data
return RedirectToAction("Index");
}
}
return View(question);
}
catch (DbUpdateException /* ex */)
{
ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator.");
}
return View();
}
And also here are my Question Model:
public class Question
{
public Question()
{
Answers = new List<Answer>();
}
public int Id { get; set; }
public string Text { get; set; }
public virtual List<Answer> Answers { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public Boolean Active { get; set; }
public string SelectedAnswer { set; get; }
}
Here is my Answer Model:
public class Answer
{
public int Id { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public List<Vote> Votes { get; set; }
}
And here is my Vote Model
public int Id { get; set; }
public string IpAdress { get; set; }
public DateTime VoteDate { get; set; }
public List<Question> Questions { set; get; }
public Vote()
{
Questions = new List<Question>();
}
}
My objective right now is to receive the vote from the Vote.Cshtml by the way here it is :
#model PoolManager.Models.Question
<div>
#Html.HiddenFor(x => x.Id)
<h3> #Model.Text </h3>
#foreach (var a in Model.Answers)
{
<p>
#Html.RadioButtonFor(b => b.SelectedAnswer, a.Id) #a.Text
#Model.SelectedAnswer
</p>
<input type="submit" />
}
So my objective is to receive the vote for each question and add the vote to the db, I don't know what i'm doing wrong..

Related

How to get data from list by condition in Xamarin

I have Class Model:
Class ProductInfo
public class ProductInfo
{
public int ID { get; set; }
public int IDProduct { get; set; }
public List<ProductImages> ProductImages { get; set; }
}
Class ProductImages
public class ProductImages
{
public int ID { get; set; }
public int ProductID { get; set; }
public string Images { get; set; }
public Boolean ImgFlag { get; set; }
}
I have data
This is how I get product information
async Task ExecuteLoadProductCommand()
{
IsBusy = true;
try
{
ProductInfos.Clear();
var prodList = await productRepository.GetProductsAsync();
foreach (var prod in prodList)
{
//Get Imgaes by condition
//prod.Images = ProductImages()
ProductInfos.Add(prod);
}
}
catch (Exception)
{
throw;
}
finally
{
IsBusy = false;
}
}
The first:
How can I Binding Images with the condition ImgFlag = true in ContentPage Product.axml
The Second:
I have a ContentPage that shows ProductDetails.axml. I show the following information:
"Name": Name Product,... ---> This is fine. However I have an extra CarouselView. I want to show a list of images with the condition that ProductID = ID(ProductInfo)
This is how I pass the ProductDetail data
public DashboardsViewModel()
{
LoadProductCommand = new Command(async () => await ExecuteLoadProductCommand());
ProductInfos = new ObservableCollection<ProductInfo>();
ProductTappedView = new Command<ProductInfo>(OnViewDetailProduct);
}
private async void OnViewDetailProduct(ProductInfo prod)
{
await Navigation.PushAsync(new DetailProduct(prod));
}
Thank you!

Do I need set primary key in join table? MVC many to many relationship

As in question: is primary key in join table needed?
I have job table:
public partial class Job
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Job()
{
this.Room = new HashSet<Room>();
}
public int JobID { get; set; }
public string Title { get; set; }
public Nullable<int> DepartmentID { get; set; }
public virtual Department Department { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Room> Room { get; set; }
}
And user table:
public partial class AspNetUsers
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public AspNetUsers()
{
this.Department = new HashSet<Department>();
}
public string Id { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<int> PhoneNo { get; set; }
public Nullable<System.DateTime> HireDate { get; set; }
public Nullable<System.DateTime> BirthDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Department> Department { get; set; }
}
Every user can be in few departments, and every deparment can have many users.
In my controller:
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.Web;
using System.Web.Mvc;
using Praca.Models;
using Praca.ViewModels;
namespace Praca.Controllers
{
public class EmployeeController : Controller
{
private Entities1 db = new Entities1();
// GET: Employee
public ActionResult Index(string id)
{
var viewModel = new AspNetUserDepartmentVM();
viewModel.AspNetUsers = db.AspNetUsers
.Include(i => i.Department)
.OrderBy(i => i.LastName);
if (id != null)
{
ViewBag.EmployeeID = id;
viewModel.Departments = viewModel.AspNetUsers.Where(
i => i.Id == id).Single().Department;
}
return View(viewModel);
}
// GET: Employee/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
// GET: Employee/Create
public ActionResult Create()
{
return View();
}
// POST: Employee/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName,FirstName,LastName,PhoneNo,HireDate,BirthDate")] AspNetUsers aspNetUsers)
{
if (ModelState.IsValid)
{
db.AspNetUsers.Add(aspNetUsers);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(aspNetUsers);
}
// GET: Employee/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers
.Include(i => i.Department)
.Where(i => i.Id == id)
.Single();
PopulateAssignedCourseData(aspNetUsers);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
private void PopulateAssignedCourseData(AspNetUsers aspNetUsers)
{
var allCourses = db.Department;
var instructorCourses = new HashSet<int>(aspNetUsers.Department.Select(c => c.DepartmentID));
var viewModel = new List<AssignedDepartment>();
foreach (var course in allCourses)
{
viewModel.Add(new AssignedDepartment
{
DepartmentID = course.DepartmentID,
DepartmentName = course.DepartmentName,
Assigned = instructorCourses.Contains(course.DepartmentID)
});
}
ViewBag.Courses = viewModel;
}
// POST: Employee/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string id, string[] selectedCourses)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var instructorToUpdate = db.AspNetUsers
.Include(i => i.Department)
.Where(i => i.Id == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "",
new string[] { "LastName"}))
{
try
{
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}
private void UpdateInstructorCourses(string[] selectedCourses, AspNetUsers instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.Department = new List<Department>();
return;
}
var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.Department.Select(c => c.DepartmentID));
foreach (var course in db.Department)
{
if (selectedCoursesHS.Contains(course.DepartmentID.ToString()))
{
if (!instructorCourses.Contains(course.DepartmentID))
{
instructorToUpdate.Department.Add(course);
}
}
else
{
if (instructorCourses.Contains(course.DepartmentID))
{
instructorToUpdate.Department.Remove(course);
}
}
}
}
// GET: Employee/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
if (aspNetUsers == null)
{
return HttpNotFound();
}
return View(aspNetUsers);
}
// POST: Employee/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
AspNetUsers aspNetUsers = db.AspNetUsers.Find(id);
db.AspNetUsers.Remove(aspNetUsers);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}`
Unfortunately I have error: Unable to update the EntitySet 'AspNetUsersDepartment' because it has a DefiningQuery and no element exists in the element to support the current operation.
How can I solve this problem?
When i set primary key on that table, there is no many to many relationship but two one to many's relations.
OK. I have figuerd it out for myself..
If anyone also have this kind of problem:
You have to set primary keys, but not as separate value in your table.
In my case
CONSTRAINT [PK_dbo.AspNetUserDepartment] PRIMARY KEY CLUSTERED ([EmployeeId] ASC, [DepartmentId] ASC),
works perfectly.

Allow user to edit list items in MVC?

I'm using Entity Framework Core to build a simple web app. For this app, I've created a model called Company that includes basic business info + a list of contacts (sales reps).
Here's my model:
public class Company
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Promo { get; set; }
public virtual List<Contact> Contacts { get; set; }
}
public class Contact
{
[Key]
public int ContactID { get; set; }
[ForeignKey("Company")]
public int CompanyID { get; set; }
public virtual Company Company { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
}
Here's the controller's index() method:
// GET: Companies
public async Task<IActionResult> Index()
{
List<Company> viewModelData = await _context.Companies
.Include(c => c.Contacts)
.ToListAsync();
return View(viewModelData);
}
Edit method:
// GET: Companies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var company = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
if (company == null)
{
return NotFound();
}
return View(company);
}
// POST: Companies/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, [Bind("ID,Name,Promo,Contacts")] Company company)
{
if (id == null)
{
return NotFound();
}
var companyToUpdate = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
if (await TryUpdateModelAsync<Company>(
companyToUpdate,
"",
i => i.Name, i => i.Promo, i => i.Contacts
)) {
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
return RedirectToAction("Index");
}
return View(companyToUpdate);
}
This is not correct since the code only allows me to edit Company info. How do I modify the code so that I can edit both Company & its contacts on the same edit view?
If you're purely looking to update values, then you can explicitly update them like so. A View Model is also recommended but this comes down to good vs bad practice. This omits the exception handling and serves only as an example of how to map these values, you'll have to modify the remainder of your controller to work directly with the CompanyEditViewModel
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int? id, [Bind("ID,Name,Promo,Contacts")] CompanyEditViewModel company)
{
if (!ModelState.IsValid)
return RedirectToAction("Index");
var companyToUpdate = await _context.Companies
.Include(v => v.Contacts)
.FirstOrDefaultAsync(m => m.ID == id);
// Assign the new values
companyToUpdate.Name = company.Name;
companyToUpdate.Promo = company.Promo;
companyToUpdate.Contacts = company.Contacts?.ToList();
// Update and save
_context.Companies.Update(companyToUpdate);
await _context.SaveChangesAsync();
return View(companyToUpdate);
}
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public string Promo { get; set; } // Yes or No field
public List<Contact> Contacts { get; set; }
public class Contact
{
[Key]
public int ContactID { get; set; }
public int CompanyID { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
}
}
// The View Model contains the Company details which were modified
// The first Edit method will have to be updated to bind this View Model to the view
public class CompanyEditViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public string Promo { get; set; }
public IList<Company.Contact> Contacts { get; set; }
}

Invalid modelstate: how to return to view when I have dropdownlists?

I have a big view with more than 40 fields. Some of these fields are dropdownlists, that I populate with a list of selectlistitems.
I am using the annotations on my viewmodel, to make some of them required.
Now I want to make the ModelState.IsValid check, and return to the original view with errors if there is some errors.
Problem is, if I simply make a return View(model), all my dropdownlists will crash the site, as they need to be populated again to load the page.
So my question is: how do i handle the return when modelstate is invalid.
My controller:
public ActionResult CreateSelling(SellingAdViewModel model)
{
if (ModelState.IsValid)
{
SellingAdvert sellingAdvert = setSellingAd(model);
var stored_advert = sellingAdvertService.Create(sellingAdvert);
if (User != null && User.Identity.IsAuthenticated)
{
if (model.AcceptPartner)
{
notifyPartner(stored_advert);
}
return RedirectToAction("Upgrade", "Ads", new { AdvertID = stored_advert.Id });
}
else
{
return RedirectToAction("ActivateAnonymous", "Ads", new { AdvertID = stored_advert.Id, anonymousId = model.UserId, AdvertType = "selling" });
}
}
return View(model);
}
My viewmodel (I have a SellingAdViewModel that derives from this one and add more properties):
public class BasicAdViewModel
{
public int SectorId { get; set; }
public Guid UserId { get; set; }
public bool IsAnonymousUser { get; set; }
public int AdvertId { get; set; }
[DisplayName("Titel:")]
[Required(ErrorMessage = "Titel skal udfyldes")]
public string Headline { get; set; }
[DisplayName("Beskrivelse:")]
[StringLength(50, ErrorMessage = "Beskrivelsen minimum fylde 50 karakterer")]
public string Description { get; set; }
[DisplayName("Søgeord:")]
public string SearchWords { get; set; }
[DisplayName("Undertitel:")]
public string Subtitle { get; set; }
[DisplayName("Type af drift")]
public List<SelectListItem> OperationTypes { get; set; }
[Required]
public int SelectedOperationTypeId { get; set; }
[Required]
public int SelectedSectorId { get; set; }
public IEnumerable<GroupedSelectListItem> Sectors { get; set; }
}
Setting my dropdownlists in the first place:
My model has the List<SelectListItem> properties, and I fill them by having a couple of helper methods:
SellingAdViewModel model = new SellingAdViewModel()
{
BusinessEntityTypes = ModelListHelpers.GetBusinessEntityTypes(),
FoundedYears = ModelListHelpers.GetFoundedYears(null),
ReasonForSale = ModelListHelpers.GetReasonForSale(),
RevenuePrediction = ModelListHelpers.GetRevenuePrediction(),
RevenueStatus = ModelListHelpers.GetRevenueStatus(),
OperationTypes = ModelListHelpers.GetOperationTypes(),
Region = ModelListHelpers.GetRegions(),
Turnover = ModelListHelpers.Turnovers(),
OperatingIn = ModelListHelpers.OperatingIn(),
AmountOfEmployees = ModelListHelpers.GetAmountOfEmployees()
};
I suggest you this solution put your model in a TempData during your GET action And if the model state is invalid you make an assignment like this
public ActionResult CreateSelling(SellingAdViewModel model)
{
if (ModelState.IsValid)
{
SellingAdvert sellingAdvert = setSellingAd(model);
var stored_advert = sellingAdvertService.Create(sellingAdvert);
if (User != null && User.Identity.IsAuthenticated)
{
if (model.AcceptPartner)
{
notifyPartner(stored_advert);
}
return RedirectToAction("Upgrade", "Ads", new { AdvertID = stored_advert.Id });
}
else
{
return RedirectToAction("ActivateAnonymous", "Ads", new { AdvertID = stored_advert.Id, anonymousId = model.UserId, AdvertType = "selling" });
}
}
model.YourList = TempData.Peek("YourList");
return View(model);
}

Add in one controller checking other controller (asp.net mvc)

I have two model in my project, SupplierRow.cs
using System;
namespace Argussite.SupplierServices.ViewModels
{
public class SupplierRow
{
public Guid Id { get; set; }
public string FullName { get; set; }
public bool Subscribed { get; set; }
public bool Active { get; set; }
public int Visits { get; set; }
}
}
and UserRow.cs
using System;
namespace Argussite.SupplierServices.ViewModels
{
public class UserRow
{
public Guid Id { get; set; }
public string FullName { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Status { get; set; }
public int Role { get; set; }
}
}
then I use the first model in one controller
public ActionResult Grid(bool? active)
{
var page = Context.Suppliers.AsNoTracking()
.WhereIf(active != null, e => e.Active == active)
.Select(e => new SupplierRow
{
Id = e.Id,
FullName = e.FullName,
Active = e.Active,
Visits = e.Visits
})
.ToList();
return PartialView("_Grid", page);
}
and use the second model in other controller
public class AdminSuppliersAccountsController : BaseController
{
public ActionResult Index(Guid id)
{
var supplierOfUser = Context.Suppliers.AsNoTracking()
//.Include(e => e.Supplier)
.FirstOrDefault(e => e.Id == id);
ViewData.Add("id", id);
ViewData.Add("SupplierFullName", supplierOfUser.FullName);
return View();
}
public ActionResult Grid(int? status, Pager pager, Guid? supplierId)
{
var page = Context.Users.AsNoTracking()
.Where(e => e.SupplierId == supplierId)
.WhereIf(status != null, e => (e.Status == status))
.Select(e => new UserRow
{
Id = e.Id,
FullName = e.FullName,
Email = e.Email,
Name = e.Name,
Status = e.Status,
Role = e.Role
})
.GetPage(pager, Sorter.Asc<UserRow, string>(e => e.FullName));
return PartialView("_Grid", page);
}
but I need to add in the first controller checking if all users from second model have status Inactive and then use that in the view.
How can I do that?
I guess, I need to add a new property in the first model public bool AllUnactive { get; set; } but what should I do then?

Resources