Getting error on posting data in Umbraco - c#

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.

Related

ASP.Net Core 3.1 Razor Pages and CRUD operation with Dapper

I am beginner to ASP.Net Core 3.1 and have to use Dapper in our project which need to be upgraded from webform to asp.net core 3.1 using Dapper as we use lot of store procedure and CTE queries on some page. We also have lot of data which is frequently queries.
I am at a very beginner level with no experience in MVC so my focus is on ASP.Net Core 3.1 razor pages using dapper, Unfortunately i am not abel to find complete tutorials on net with using Razor pages & dapper. Most o fthe example & tutorials are for ASP.net core MVC & EF based.
I am trying to convert Blazor dapper example into asp.net core razor pages and i am stuck on how to show data on employee.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BookListRazor.Data;
using BookListRazor.Model;
namespace BookListRazor.Pages
{
public class EmployeeModel : PageModel
{
private readonly SqlConnectionConfiguration _configuration;
public EmployeeModel(SqlConnectionConfiguration configuration)
{
_configuration = configuration;
}
public IEnumerable<Employee> EmployeeList{ get; set; }
public IEmployeeService _employeeService;
public async Task OnGet()
{
EmployeeList = await _employeeService.GetEmployees();
}
}
}
I am not able to make a call to GetEmployees() function in EmployeeDapperService.cs class. I need help so that i can list all employee and from there i will also work on Insert & Update.
Below is the complete code for project
Folder Structure & files
-Data
--EmployeeDapperService.cs
--IEmployeeService.cs
--SqlConnectionConfiguration.cs
-Model
--Employee.cs
-Pages
--Index.cshtml
--Employee.cshtml
Startup.cs
EmployeeDapperService.cs
using Dapper;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using BookListRazor.Model;
using BookListRazor.Data;
namespace BookListRazor.Data
{
public class EmployeeDapperService : IEmployeeService
{
private readonly SqlConnectionConfiguration _configuration;
public EmployeeDapperService(SqlConnectionConfiguration configuration)
{
_configuration = configuration;
}
public async Task<bool> CreateEmployee(Employee employee)
{
using (var conn = new SqlConnection(_configuration.Value))
{
const string query = #"insert into dbo.Employees (Id,Name,Department,Designation,Company,City) values(#Id,#Name,#Department,#Designation,#Company,#City)";
conn.Open();
try
{
await conn.ExecuteAsync(query, new { Id = Guid.NewGuid().ToString(), employee.Name, employee.Department, employee.Designation, employee.Company, employee.City }, commandType: CommandType.Text);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
return true;
}
public async Task<bool> DeleteEmployee(string id)
{
using (var conn = new SqlConnection(_configuration.Value))
{
const string query = #"delete dbo.Employees where Id=#Id";
conn.Open();
try
{
await conn.ExecuteAsync(query, new { id }, commandType: CommandType.Text);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
return true;
}
public async Task<bool> EditEmployee(string id, Employee employee)
{
using (var conn = new SqlConnection(_configuration.Value))
{
const string query = #"update dbo.Employees set Name = #Name, Department = #Department, Designation = #Designation, Company = #Company, City = #City where Id=#Id";
conn.Open();
try
{
await conn.ExecuteAsync(query, new { employee.Name, employee.Department, employee.Designation, employee.Company, employee.City, id }, commandType: CommandType.Text);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
return true;
}
public async Task<List<Employee>> GetEmployees()
{
IEnumerable<Employee> employees;
using (var conn = new SqlConnection(_configuration.Value))
{
const string query = #"select * from dbo.Employees";
conn.Open();
try
{
employees = await conn.QueryAsync<Employee>(query, commandType: CommandType.Text);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
return employees.ToList();
}
public async Task<Employee> SingleEmployee(string id)
{
Employee employee = new Employee();
using (var conn = new SqlConnection(_configuration.Value))
{
const string query = #"select * from dbo.Employees where Id=#Id";
conn.Open();
try
{
employee = await conn.QueryFirstOrDefaultAsync<Employee>(query, new { id }, commandType: CommandType.Text);
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
return employee;
}
}
}
IEmployeeService.cs
using BookListRazor.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookListRazor.Data
{
public interface IEmployeeService
{
Task<List<Employee>> GetEmployees();
Task<bool> CreateEmployee(Employee employee);
Task<bool> EditEmployee(string id, Employee employee);
Task<Employee> SingleEmployee(string id);
Task<bool> DeleteEmployee(string id);
}
}
SqlConnectionConfiguration.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookListRazor.Data
{
public class SqlConnectionConfiguration
{
public SqlConnectionConfiguration(string value) => Value = value;
public string Value { get; }
}
}
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BookListRazor.Model
{
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Designation { get; set; }
public string Company { get; set; }
public string City { get; set; }
}
}
Startup.cs partial code
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IEmployeeService, EmployeeDapperService>();
var sqlConnectionConfiguration = new SqlConnectionConfiguration(Configuration.GetConnectionString("SqlDbContext"));
services.AddSingleton(sqlConnectionConfiguration);
services.AddControllersWithViews();
services.AddRazorPages().AddRazorRuntimeCompilation();
}
Employee.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BookListRazor.Data;
using BookListRazor.Model;
namespace BookListRazor.Pages
{
public class EmployeeModel : PageModel
{
//for Dapper
private readonly SqlConnectionConfiguration _configuration;
public IEnumerable<Employee> EmployeeList{ get; set; }
public readonly IEmployeeService _employeeService;
public async Task OnGet()
{
// Employees = await employees.
// Employees = await
EmployeeList = await _employeeService.GetEmployees();
}
}
}
From your image above and the VisualStudio intellicense I get the feeling that you are trying to call instance methods without having an instance of EmployeeDapperService.
If that is the case you will need to inject it from the constructor of your employee.cshtml.cs page model and add a transient mapping in your startup ConfigureServices like services.AddTransient<IEmployeeService,EmployeeDapperService>();
edit
Employee.cshtml.cs
public class EmployeeModel : PageModel
{
public IEnumerable<Employee> Employees { get; set; }
public IEmployeeService EmployeeService { get; }
public EmployeeModel(IEmployeeService employeeService) {
EmployeeService = employeeService ?? throw new ArgumentNullException(nameof(employeeService));
}
public async Task OnGet()
{
Employees = await EmployeeService.GetEmployees();
}
}

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;
}
}

error when trying to add object to dictionary

I got a code with a list which im trying to change to dictionary. my problem its that in 'BankRates.cs' i fail to add objects to my dictionary. i get error :no overload of method 'Add' takes 1 argument...can some explain why?? (i understand i should add a string to the function but when i try to add empty one to make it compile, the dictionary contains only one nonfunctional object)
i have this 4 cs files:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Converter
{
class Currency
{
//members
//getters and setters
public string Code { get; set; }
public string Name { get; set; }
public double Rate { get; set; }
public double Unit { get; set; }
public string Country { get; set; }
//constractor
public Currency(string code, string name, double rate, double unit, string country)
{
this.Code = code;
this.Name = name;
this.Rate = rate;
this.Unit = unit;
this.Country = country;
}
//override ToString method for visualization
public override string ToString()
{
return (Name + "-" +Code);
}
}
}
currencyDictionary:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Converter
{
class CurrencyDic
{
//setter and getter
public Dictionary<string,Currency> currencyDic { get; set; }
//constractor
public CurrencyDic()
{
currencyDic = new Dictionary<string,Currency>();
}
public CurrencyDic(Dictionary<string,Currency> cur)
{
currencyDic = new Dictionary<string,Currency>(cur);
}
// implements foreach
public IEnumerator<Currency> GetEnumerator()
{
foreach (Currency cur in currencyDic.Values) { yield return cur;}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Converter
{
interface IBankRates
{
void GetRates();
double Convert(Currency from, Currency to, double amount);
}
}
and the last one:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.IO;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.Remoting.Messaging;
namespace Converter
{
class BankRates:IBankRates
{
private string Bank_URL = "http://www.boi.org.il/currency.xml";
CurrencyDic currencyDic = new CurrencyDic();
public void GetRates()
{
XDocument xdoc = new XDocument();
try
{
xdoc = XDocument.Load(Bank_URL);}
catch (XmlException)
{
MessageBox.Show("Failed to load Xml file");
System.Environment.Exit(1);
}
//load the xml
var allCurencies = from currency in xdoc.Descendants("CURRENCY") //linq query
select new
{
Name = currency.Descendants("NAME").First().Value,
Unit = currency.Descendants("UNIT").First().Value,
Code = currency.Descendants("CURRENCYCODE").First().Value,
Cuntry = currency.Descendants("COUNTRY").First().Value,
Rate = currency.Descendants("RATE").First().Value
};
foreach (var currency in allCurencies)
{
currencyDic.currencyDic.Add(new Currency(currency.Code, currency.Name,
double.Parse(currency.Rate),
double.Parse(currency.Unit), currency.Cuntry));
}
}
//returns the list
public CurrencyDic getDic()
{
return currencyDic;
}
//makes the converting calculation
public double Convert(Currency from,Currency to, double amount)
{
double inRate, outRate, excangeRate;
inRate = from.Rate / from.Unit;
outRate = to.Rate / to.Unit;
excangeRate = inRate / outRate;
return (amount * excangeRate);
}
}
}

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

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");
}

Categories

Resources