Cannot convert from 'System.Web.Mvc.FormCollection' to 'MyProject.Models.EditViewModel' - c#

I get two following errors in my ASP.NET MVC 3 project:
Error 1 The best overloaded method match for
'SklepAlfa.Models.ProduktyController.Edytuj(int,
SklepAlfa.Models.ProduktyEdytujViewModel)' has some invalid arguments
Error 2 Argument 2: cannot convert from
'System.Web.Mvc.FormCollection' to
'SklepAlfa.Models.ProduktyEdytujViewModel'
Here is my ProduktyEdytujViewModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SklepAlfa.Models;
using System.Web.Mvc;
namespace SklepAlfa.Models
{
public class ProduktyEdytujViewModel
{
public Produkty Produkt { get; set; }
public int id_produktu { get; set; }
public IEnumerable<Kategorie_produktow> Kategorie { get; set; }
}
}
And here it is used in my controller:
public ActionResult Edytuj(int id) //Edit
{
var model = new ProduktyEdytujViewModel //ProductsEditViewModel
{
Produkt = sklepBaza.PobierzProduktWgId(id), //GetProductById
Kategorie = sklepBaza.PobierzKategorieProduktow() //GetProductCategories
};
return View(model);
}
[HttpPost]
public ActionResult Edytuj(int id, ProduktyEdytujViewModel model)
{
if (!ModelState.IsValid)
{
model.Produkt = sklepBaza.PobierzProduktWgId(id);
model.Kategorie = sklepBaza.PobierzKategorieProduktow();
return View(model);
}
return RedirectToAction("Kategorie");
}
What am I doing wrong? Thank you in advance.

In the post action you can pass just the model object and it will contain the id
[HttpPost]
public ActionResult Edytuj(ProduktyEdytujViewModel model)
{
if (!ModelState.IsValid)
{
model.Produkt = sklepBaza.PobierzProduktWgId(model.id);
model.Kategorie = sklepBaza.PobierzKategorieProduktow();
return View(model);
}
return RedirectToAction("Kategorie");
}

Related

DotNet Entity Framework on VSCode Mac -- (Table)Exists() does not exist in current context in Controller

I am following along with the dotnet Microsoft tutorial docs. My one disadvantage is that I'm on a Mac using VS Code. At one point in the tutorial there was a scaffolding command that did not work in VS Code. So far, everything else has worked, but I'm wondering if something is missing in my Controller and that is why I am getting this error. I copy and pasted directly from the Docs. Although, the error infers that it is a syntax issue with the try/catch statement. (which I have reviewed and everything looks in order)
Here is my Controller:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using virus_mvc.Models;
using System.Text.Encodings.Web;
using virus_mvc.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace virus_mvc.Controllers
{
public class VirusDataController : Controller
{
public async Task<IActionResult> Index()
{
return View(await _context.VirusData.ToListAsync());
}
//
// GET: /HelloWorld/Welcome/
public IActionResult Welcome(string name, int numTimes = 1)
{
ViewData["Message"] = "Hello " + name;
ViewData["NumTimes"] = numTimes;
return View();
}
// GET: VirusData/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var virus = await _context.VirusData
.FirstOrDefaultAsync(m => m.Id == id);
if (virus == null)
{
return NotFound();
}
return View(virus);
}
// GET: Movies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var virus = await _context.VirusData.FindAsync(id);
if (virus == null)
{
return NotFound();
}
return View(virus);
}
// POST: Movies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Title,ReleaseDate,Genre,Price")] VirusData virus)
{
if (id != virus.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(virus);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
**if (!VirusDataExists(virus.Id))** -- this is the line throwing the error
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(virus);
}
private readonly virus_mvcContext _context;
public VirusDataController(virus_mvcContext context)
{
_context = context;
}
}
}
Here is my Error:
/Users/katie/C_sharp/virus_backend/virus_mvc/Controllers/VirusDataController.cs(89,26): error CS0103: The name 'VirusDataExists' does not exist in the current context [/Users/katie/C_sharp/virus_backend/virus_mvc/virus_mvc.csproj]
Here's my Model:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using virus_mvc.Data;
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace virus_mvc.Models
{
public class VirusData
{
public int Id { get; set; }
public string Title { get; set; }
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }
}
}

Unable to get values from view

I am learning about Unit of work, repository and service. Now I don't know why the values entered seems to be null while login in screen
After values are entered when i give submit it shows only null in values screen
while breakpoints in controller i found that there is null.
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using ClassLibrary1;
namespace Registeration.Controllers
{
public class DbController : Controller
{
// GET: Db
public ActionResult Index()
{
Service obj = new Service();
var lis = obj.GetAllLogins();
return View(lis);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Mdl Obj)
{
Service obj1 = new Service();
var details = obj1.CreateEmp(Obj);
return RedirectToAction("Index");
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(string userName, string dpt)
{
Service obj = new Service();
var res = obj.Login(userName, dpt); //values shows null
if (res != null)
{
return RedirectToAction("Index");
}
return RedirectToAction("Login");
}
}
}
Service Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using DataAccess;
using DataAccess.UoW;
using Model;
namespace ClassLibrary1
{
public class Service
{
private readonly Unit _uow;
public Service()
{
_uow = new Unit();
}
public IEnumerable<Mdl> GetAllLogins()
{
var logins = _uow.Register.GetAll().ToList();
if (logins.Any())
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Table_1, Mdl>();
});
IMapper mapper = config.CreateMapper();
var dest = mapper.Map<List<Table_1>, List<Mdl>>(logins);
return dest;
}
return null;
}
public Mdl Login(string userName,string dpt)
{
var logins = _uow.Register.Get(x=>x.Name==userName && x.Deprmt==dpt);
if (logins != null)
{
var obj1 = new Mdl();
if (logins.Id > 0)
return obj1;
}
return null;
}
}
}
Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class Mdl
{
public int Id { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public string Deprmt { get; set; }
public string State { get; set; }
}
}
You have not shown you view code here, If it on login[POST] method then, it may be possible you are not using name attribute in your html control.
Controls should have the same name as your params(userName, dpt) so that ModelBinder can bind them.

Xamarin.Forms: How to have a Pie Chart using data from the Database?

I'm creating a Xamarin.Forms Portable Application wherein I was able to display a Pie Chart using OxyPlot. My chart only has pre-defined items. What I want to do is to make the items from my DATABASE in Visual Studio to be displayed on the Chart and not the pre-defined items.
I have 2 projects in one Solution. The WebFormsProject and the Xamarin.Forms (Portable)
In my WebFormsProject, I created a SalesController where I used LINQ expression to get all the data in the database that I need. I also created a SalesViewModel there where I have declared all the Properties I have. I tried to test it in my WEB API if it does return a value or not, and IT DOES RETURN A VALUE.
In my PORTABLE project, I have a created Sales model that has exactly the same Properties with my SalesViewModel in the WebFormsProject. I also have a SalesVM.cs wherein I tried to access the records from the WebFormsProject by using SalesServices and RestClient.
I have tried using these codes but it didn't work. What do you think is the reason behind this?
Here are my codes:
WebForms
1.) SalesViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebFormsDemo.ViewModel
{
public class SalesViewModel
{
public int Id { get; set; }
public int ORDER_ID { get; set; }
public int ORDER_DETAILS_ID { get; set; }
public int PRODUCT_ID { get; set; }
public string PRODUCT_CODE { get; set; }
public string NET_AMOUNT { get; set; }
}
}
2.) SalesController.cs
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 WebFormsDemo;
using WebFormsDemo.ViewModel;
namespace WebFormsDemo.Controllers
{
public class SalesController : ApiController
{
private EBMSEntities db = new EBMSEntities();
// GET: api/Sales
public IQueryable<SalesViewModel> GetSalesViewModels()
{
//return db.SalesViewModels;
var sales = from order in db.ORDERs
join order_detail in db.ORDER_DETAILS
on order.ORDER_ID equals order_detail.ORDER_ID
join prod in db.PRODUCTs
on order_detail.PRODUCT_ID equals prod.PRODUCT_ID
orderby order_detail.TOTAL_AMT_PER_ITEM descending
//group prod by prod.PRODUCT_CODE
group order_detail by prod.PRODUCT_CODE into od
select new SalesViewModel
{
PRODUCT_CODE = od.Key,
NET_AMOUNT = od.Sum(p => p.TOTAL_AMT_PER_ITEM).ToString(),
};
return sales;
}
// GET: api/Sales/5
[ResponseType(typeof(SalesViewModel))]
public IHttpActionResult GetSalesViewModel(int id)
{
SalesViewModel salesViewModel = db.SalesViewModels.Find(id);
if (salesViewModel == null)
{
return NotFound();
}
return Ok(salesViewModel);
}
// PUT: api/Sales/5
[ResponseType(typeof(void))]
public IHttpActionResult PutSalesViewModel(int id, SalesViewModel salesViewModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != salesViewModel.Id)
{
return BadRequest();
}
db.Entry(salesViewModel).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!SalesViewModelExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Sales
[ResponseType(typeof(SalesViewModel))]
public IHttpActionResult PostSalesViewModel(SalesViewModel salesViewModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.SalesViewModels.Add(salesViewModel);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = salesViewModel.Id }, salesViewModel);
}
// DELETE: api/Sales/5
[ResponseType(typeof(SalesViewModel))]
public IHttpActionResult DeleteSalesViewModel(int id)
{
SalesViewModel salesViewModel = db.SalesViewModels.Find(id);
if (salesViewModel == null)
{
return NotFound();
}
db.SalesViewModels.Remove(salesViewModel);
db.SaveChanges();
return Ok(salesViewModel);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool SalesViewModelExists(int id)
{
return db.SalesViewModels.Count(e => e.Id == id) > 0;
}
}
}
.
XamarinFormsPortable
1.) Sales.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XamarinFormsDemo.Models
{
public class Sales
{
public int Id { get; set; }
public int ORDER_ID { get; set; }
public int ORDER_DETAILS_ID { get; set; }
public int PRODUCT_ID { get; set; }
public string PRODUCT_CODE { get; set; }
public double NET_AMOUNT { get; set; }
}
}
2.) SalesVM.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OxyPlot;
using OxyPlot.Series;
using OxyPlot.Xamarin.Forms;
using Xamarin.Forms;
using System.Runtime.CompilerServices;
using XamarinFormsDemo.Models;
using System.Collections.ObjectModel;
using XamarinFormsDemo.Services;
namespace XamarinFormsDemo.ViewModels
{
public class SalesVM
{
private List<Sales> salesmodel { get; set; }
public List<Sales> SalesModelvm
{
get
{
return salesmodel;
}
set
{
salesmodel = value;
OnPropertyChanged();
}
}
public SalesVM()
{
InitializeDataAsync();
}
private async Task InitializeDataAsync()
{
var salesServices = new SalesServices();
SalesModelvm = await salesServices.GetSalesAsync();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
3.) SalesServices.cs
using Plugin.RestClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;
namespace XamarinFormsDemo.Services
{
public class SalesServices
{
public async Task<List<Sales>> GetSalesAsync()
{
RestClient_Sales<Sales> restClient = new RestClient_Sales<Sales>();
var salesList = await restClient.GetSalesAsync();
return salesList;
}
}
}
4.) RestClient.cs
public class RestClient_Sales<T>
{
private const string WebServiceUrl = "http://localhost:50857/api/Sales/";
public async Task<List<T>> GetSalesAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
}

Make List of Items C# MVC [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a very big issuse here. I'm trying to make a list off all cars and push them to View, but it doesn't work as I assume. Any idea how can I do that ?? I would be very thankfull
Here is my Car Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Automarket.Models;
using System.Data.Entity;
using System.Web.Script.Serialization;
using System.Net;
namespace Automarket.Controllers
{
public class CarController : Controller
{
OurDBContext db = new OurDBContext();
private object Viewbag;
private readonly object ds;
// GET: Automarket
public ActionResult Index()
{
List<Marke> marke = db.Marke.ToList();
List<Modeli> modeli = db.Modeli.ToList();
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string deps = oSerializer.Serialize(modeli);
ViewData["deps"] = deps;
ViewData["marke"] = marke;
ViewData["modeli"] = modeli;
return View(db.car.ToList());
}
// GET: Cars/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// GET: Cars/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarID,Make,Model,Price,Registration,Mileage,FuealType,Country,ZipCode,Picture")] Car car)
{
if (ModelState.IsValid)
{
db.car.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
// GET: Cars/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CarID,Make,Model,Price,Registration,Mileage,FuealType,Country,ZipCode,Picture")] Car car)
{
if (ModelState.IsValid)
{
db.Entry(car).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// POST: Cars/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Car car = db.car.Find(id);
db.car.Remove(car);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Here is my Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Automarket.Models
{
public class Car
{
public int CarID { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public float Price { get; set; }
public int Registration { get; set; }
public double Mileage { get; set; }
public string FuealType { get; set; }
public string Country { get; set; }
public int ZipCode { get; set; }
public string pathToImage { get; set; }
}
}
To show a list of objects in your view, bascally, you need:
In Controller, send a list of objects to View using View(<data>) method:
public ActionResult Index() {
OurDBContext db = new OurDBContext();
return View(db.car.ToList());
}
In View, receive the list of objects in Model variable:
#model List<Car>
<html>
...
<body>
#foreach(var item in Model) {
<p>#item.Property</p>
}
</body></html>

Getting error on posting data in Umbraco

Currently I am using both controller for get(RenderMvcController) & post(SurfaceController). But I am getting an error when inserting record in database using Umbraco.Core.
Error: "No mapping exists from object type Umbraco.Web.PublishedCache.XmlPublishedCache.XmlPublishedContent to a known managed provider native type."
Model - BaseModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Web;
namespace SampleLogic.Models
{
public class BaseModel : Umbraco.Web.Models.RenderModel
{
public BaseModel()
: base(UmbracoContext.Current.PublishedContentRequest.PublishedContent)
{}
}
}
Model - Category.cs
[TableName("Categories")]
[PrimaryKey("Id", autoIncrement = true)]
public class Category : BaseModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<Category> lstCategory;
public Category()
{
lstCategory = new List<Category>();
}
}
View:Sample.cshtml
#using SampleLogic
#using SampleLogic.Models
#inherits UmbracoTemplatePage
#{
Layout = "umbLayout.cshtml";
var repo = new CategoryRepository();
}
#Html.Action("AddCategory", "SampleSurface")
#foreach (var category in repo.GetAll())
{
<p>
#category.Name
#Html.ActionLink("Edit", "Sample", "Sample", new { id = #category.Id }, null)
Edit
</p>
}
Repository: CategoryRepository.cs
using SampleLogic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.DataLayer;
using Umbraco.Core;
using Umbraco.Core.Persistence;
namespace SampleLogic
{
public class CategoryRepository
{
private readonly UmbracoDatabase _database;
public CategoryRepository()
{
_database = ApplicationContext.Current.DatabaseContext.Database;
}
public List<Category> GetAll()
{
return _database.Fetch<Category>("select * from categories");
}
public Category GetCategoryById(int id)
{
return _database.FirstOrDefault<Category>("select * from categories where Id = " + id);
}
public void Insert(Category category)
{
_database.Insert(category);
}
public void Update(Category category)
{
_database.Update(category);
}
public void Delete(Category category)
{
_database.Delete(category);
}
}
}
Controller: SampleController.cs
using SampleLogic.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
namespace SampleLogic.Controllers
{
public class SampleController : RenderMvcController
{
public ActionResult Sample(int id = 0)
{
Category model = new Category();
var repo = new CategoryRepository();
if (Request.QueryString["id"] != null)
{
model.Name = repo.GetCategoryById(Convert.ToInt32(Request.QueryString["id"])).Name;
}
model.lstCategory = repo.GetAll();
return CurrentTemplate(model);
}
}
}
Controller: SampleSurfaceController.cs
using SampleLogic.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Web;
using Umbraco.Web.Mvc;
namespace SampleLogic.Controllers
{
public class SampleSurfaceController : SurfaceController
{
[HttpPost]
public ActionResult Sample(Category model)
{
var repo = new CategoryRepository();
if (model.Id > 0)
{
repo.Update(model);
}
else
{
repo.Insert(model);
}
model.Name = string.Empty;
return CurrentUmbracoPage();
}
[ChildActionOnly]
public ActionResult AddCategory(Category model)
{
if (Request.QueryString["id"] != null)
{
var repo = new CategoryRepository();
model.Name = repo.GetCategoryById(Convert.ToInt32(Request.QueryString["id"])).Name;
}
//TODO: do some searching (perhaps using Examine)
//using the information contained in the custom class QueryParameters
//return the SearchResults to the view
return PartialView("AddCategory", model);
}
}
}
I am getting error on SurfaceController when inserting or updating record.
How to resolve above issue. let me know what is the problem with code.
Now I have used SurfaceController for post & ChildActionOnly for render listing on load and removed RenderModel from model. Now its working fine for CURD operation.

Categories

Resources