Unable to get values from view - c#

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.

Related

XML Writer not working in C# ( with-in a .NET MVC web application )

I am trying to read and write to an XML file within a .NET MVC web application. The XML reader ( GetScoresXMLReader() ) is working - it is able to output to a web page. But the XML writer ( AddScoresXMLWriter ) is not working for the form page. Can anyone tell me what i am doing wrong please? Below is the User class which defines the XML methods and the controller class ( for the AddACustomer view ) from which I am calling the XML methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
namespace WebApplication10.Models
{
[Serializable]
[XmlRoot("User"), XmlType("User")]
public class Users
{
// Get the current directory.
static string path = Directory.GetCurrentDirectory();
static String binPath = path + "\\binary\\data.bin";
static String xmlPath = path + "\\Properties\\Users.xml";
[Required(ErrorMessage = "Must specifiy a first name")]
[Display(Name = "First Name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Must specifiy a last name")]
[DataType(DataType.Text)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage ="Must specifiy a role")]
[Display(Name = "Role")]
[DataType(DataType.Text)]
public string Role { get; set; }
//Parameter Less constructor needed for XML Serialization Only!!!
public Users() { }
//CONSTRUCTOR
public Users( String fname, String lname, String date)
{
FirstName = fname;
LastName = lname;
Role = date;
}
public String DisplayUser()
{
return ("First Name: " + FirstName + ", Last Name:" + LastName + ", Role: " + Role + "/n");
}
public class XMLReader
{
public static List<Users> AddScoresXMLWriter(Users userSet)
{
List<Users> userList = GetScoresXMLReader();
userList.Add(userSet);
var writer = new System.Xml.Serialization.XmlSerializer(typeof(List<Users>));
var xmlFile = new System.IO.StreamWriter(xmlPath);
writer.Serialize(xmlFile, userList);
xmlFile.Close();
return userList;
}
public static List<Users> GetScoresXMLReader()
{
List<Users> eventList = new List<Users>();
try
{
System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(List<Users>));
System.IO.StreamReader file = new System.IO.StreamReader(xmlPath);
eventList = (List<Users>)reader.Deserialize(file);
file.Close();
}
catch (FileNotFoundException fex)
{
Debug.Write(fex.Message);
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
return eventList;
}
//FOR LIST ALL CUSTOMERS PAGE
public List<Users> OutPutListOfAllUsers()
{
DataSet ds = new DataSet();//Using dataset to read xml file
ds.ReadXml(xmlPath);
var results = new List<Users>();
results = (from rows in ds.Tables[0].AsEnumerable()
select new Users
{
FirstName = rows[0].ToString(), //Convert row to int
LastName = rows[1].ToString(),
Role = rows[2].ToString(),
}).ToList();
return results;
}
}
}
}
And here is the controller from which the XML writer is called.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Web;
using Microsoft.Extensions.Logging;
using WebApplication10.Models;
using static WebApplication10.Models.Users;
namespace WebApplication10.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult ViewAllUsers()
{
XMLReader readXML = new XMLReader();
var data = readXML.OutPutListOfAllUsers();
return View(data.ToList());
}
public IActionResult AboutMe()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[HttpGet]
public ActionResult AddACustomer()
{
return View();
}
[HttpPost]
public ActionResult AddACustomer(Users user)
{
// do validation
if (!ModelState.IsValid)
{
//ADD FORM INPUT TO XML FILE
XMLReader.AddScoresXMLWriter(user);
return View(user);
}
// save user
//redirect
return Redirect("/");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
If I load ViewAllCustomers page I can see the entries that I have manually added to the XML but When I fill out all required fields of form (on AddACustomer page) it submits but the XML is not modified. If I try to submit the form incompletely then I get an error that XML file is in use.
If form submit button is clicked but form is incomplete then error is generated that XML is in use and cannot be written to.

How to manually mapping DTO WITHOUT using AutoMapper?

I'm learning C#.NET Core and trying to create DTO mapping without using AutoMapper as I'm working on a small project alone and want to understand fundamental before using extra packages, surpringly I could not easily find answer at stackoverflow.com or I may use wrong keyword searching.
BTW, below is my code which I successfully map to EmployeeForShortDto under GetEmployee method. Unfortunately, I don't how to map it under GetAllEmployee just because the return data is a collection, not a single record. Please advice.
EmployeeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetCoreWebApplication1.Dto;
using NetCoreWebApplication1.Repository;
using NetCoreWebApplication1.Other;
namespace NetCoreWebApplication1.Controller
{
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IMasterRepository _repo;
public EmployeeController(IMasterRepository repo)
{
_repo = repo;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetEmployee(int id)
{
var data = await _repo.GetEmployee(id);
if (data == null) return NotFound();
var dataDto = new EmployeeForShortDto()
{
Id = data.Id,
EmpCode = data.EmpCode,
Fname = data.Fname,
Lname = data.Lname,
Age = NetCoreWebApplication1.Other.Extension.CalcAge(data.DateBirth)
};
return Ok(dataDto);
}
[HttpGet]
public async Task<IActionResult> GetAllEmployee()
{
var data = await _repo.GetAllEmployee();
return Ok(data);
}
}
}
MasterRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NetCoreWebApplication1.Models;
namespace NetCoreWebApplication1.Repository
{
public class MasterRepository : IMasterRepository
{
private readonly PrDbContext _context;
public MasterRepository(PrDbContext context)
{
_context = context;
}
// Employee
public async Task<List<Employee>> GetAllEmployee()
{
var data = await _context.Employee.ToListAsync();
return data;
}
public async Task<Employee> GetEmployee(int id)
{
var data = await _context.Employee.FirstOrDefaultAsync(x => x.Id == id);
return data;
}
// Generic methods
public void Add<T>(T entity) where T : class
{
_context.Add(entity);
}
public void Delete<T>(T entity) where T : class
{
_context.Remove(entity);
}
public async Task<bool> SaveAll()
{
return await _context.SaveChangesAsync() > 0;
}
}
}
You can use an extension method to map from your entity type to your DTO type.
public static EmployeeForShortDto ToDto(this Employee employee)
{
if (employee != null)
{
return new EmployeeForShortDto
{
Id = employee.Id,
EmpCode = employee.EmpCode,
Fname = employee.Fname,
Lname = employee.Lname,
Age = NetCoreWebApplication1.Other.Extension.CalcAge(employee.DateBirth)
};
}
return null;
}
And then use where needed.
[HttpGet("{id}")]
public async Task<IActionResult> GetEmployee(int id)
{
var data = await _repo.GetEmployee(id);
if (data == null)
{
return NotFound();
}
return Ok(data.ToDto());
}
[HttpGet]
public async Task<IActionResult> GetAllEmployee()
{
var data = await _repo.GetAllEmployee();
return Ok(data.Select(x => x.ToDto()));
}
thank you for all responses, all are very useful to me. Finally, I end up with solution from #Brad. I also learned how to make a reverse mapping from DTO to a class before adding a record to the database.
I put my code below in case someone want to see. Any comments/suggestions are more than welcome. Thank you.
Extension.cs
using NetCoreWebApplication1.Dto;
using NetCoreWebApplication1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetCoreWebApplication1.Other
{
public static class Extension
{
public static EmployeeForShortDto MapToEmployeeForShortDto(this Employee emp)
{
if (emp != null)
{
return new EmployeeForShortDto
{
Id = emp.Id,
EmpCode = emp.EmpCode,
Fname = emp.Fname,
Lname = emp.Lname,
Age = emp.DateBirth.CalcAge()
};
}
return null;
}
public static EmployeeForListDto MapToEmployeeForListDto(this Employee emp)
{
if (emp != null)
{
return new EmployeeForListDto
{
Id = emp.Id,
EmpCode = emp.EmpCode,
Fname = emp.Fname,
Lname = emp.Lname,
Age = emp.DateBirth.CalcAge(),
EntityCode = emp.EntityCode,
IsActive = emp.IsActive
};
}
return null;
}
public static Employee MapFromEmployeeForAddDto(this EmployeeForAddDto emp)
{
if (emp != null)
{
return new Employee
{
EmpCode = emp.EmpCode,
Fname = emp.Fname,
Lname = emp.Lname,
IdCard = emp.IdCard,
IsActive = 1
};
}
return null;
}
public static int CalcAge(this DateTime? dateBirth)
{
if (dateBirth.HasValue)
{
var age = DateTime.Today.Year - dateBirth.Value.Year;
if (dateBirth.Value.AddYears(age) > DateTime.Today) age--;
return age;
}
else
{
return 0;
}
}
}
}
MasterRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NetCoreWebApplication1.Dto;
using NetCoreWebApplication1.Models;
namespace NetCoreWebApplication1.Repository
{
public class MasterRepository : IMasterRepository
{
private readonly PrDbContext _context;
public MasterRepository(PrDbContext context)
{
_context = context;
}
// Employee
public async Task<List<Employee>> GetAllEmployee()
{
var data = await _context.Employee.ToListAsync();
return data;
}
public async Task<Employee> GetEmployee(int id)
{
var data = await _context.Employee.FirstOrDefaultAsync(x => x.Id == id);
return data;
}
public async Task<Employee> AddEmployee(Employee data)
{
await _context.Employee.AddAsync(data);
await _context.SaveChangesAsync();
return data;
}
public async Task<bool> EmployeeExists(string entityCode, string empCode)
{
if (await _context.Employee.AnyAsync(x =>
x.EntityCode == entityCode &&
x.EmpCode == empCode))
return true;
return false;
}
// Generic methods
public void Add<T>(T entity) where T : class
{
_context.Add(entity);
}
public void Delete<T>(T entity) where T : class
{
_context.Remove(entity);
}
public async Task<bool> SaveAll()
{
return await _context.SaveChangesAsync() > 0;
}
}
}
EmployeeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetCoreWebApplication1.Dto;
using NetCoreWebApplication1.Repository;
using NetCoreWebApplication1.Other;
using NetCoreWebApplication1.Models;
namespace NetCoreWebApplication1.Controller
{
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IMasterRepository _repo;
public EmployeeController(IMasterRepository repo)
{
_repo = repo;
}
[HttpPost("add")]
public async Task<IActionResult> AddEmployee(EmployeeForAddDto emp)
{
if (await _repo.EmployeeExists(emp.EntityCode, emp.EmpCode))
ModelState.AddModelError("Employee", "Employee is duplicate (EntityCode + EmpCode)");
if (!ModelState.IsValid)
return BadRequest(ModelState);
Employee employeeToAdd = emp.MapFromEmployeeForAddDto();
await _repo.AddEmployee(employeeToAdd);
return StatusCode(201);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetEmployee(int id)
{
var data = await _repo.GetEmployee(id);
if (data == null) return NotFound();
return Ok(data.MapToEmployeeForShortDto());
}
[HttpGet]
public async Task<IActionResult> GetAllEmployee()
{
var data = await _repo.GetAllEmployee();
//var dataDto = data.Select(x => x.MapToEmployeeForShortDto());
var dataDto = data.Select(x => x.MapToEmployeeForListDto());
return Ok(dataDto);
}
}
}
Okay, the direct answer to your question is "do it pr returned values";
List<EmployeeForShortDto> result = new List<EmployeeForShortDto>();
foreach(Employee dbEmployee in data )
{
result.add(new EmployeeForShortDto()
{
Id = dbEmployee .Id,
EmpCode = dbEmployee .EmpCode,
Fname = dbEmployee .Fname,
Lname = dbEmployee .Lname,
Age = NetCoreWebApplication1.Other.Extension.CalcAge(dbEmployee .DateBirth)
});
}
This however, is type specific for your item. Why not make a generic method that uses reflection to map the object either by attributes attached, or by property name directly?
If you get it done, you will be able to transfer any object to a DTO, as long as you adhere to the internal rules of property names or setup up the mappings via the attributes.
For your problem, extract your implementation in a new method.
EmployeeForShortDto ConvertToDto(Employee data)
{
var dataDto = new EmployeeForShortDto()
{
Id = data.Id,
EmpCode = data.EmpCode,
Fname = data.Fname,
Lname = data.Lname,
Age = NetCoreWebApplication1.Other.Extension.CalcAge(data.DateBirth)
};
}
Then finally call it in loop,
foreach(Employee e in EmployeeList)
{
dtoList.Add(ConvertToDto(e));
}
For generic implementation, Generate a list of properties of Model and Dto via reflection. and then match their types.
class AdapterHelper<T1, T2>
{
public T1 Adapt(T2 source)
{
T1 targetItem = Activator.CreateInstance<T1>();
var props = typeof(T1).GetProperties();
var targetProps = typeof(T2).GetProperties();
foreach (var prop in props)
{
foreach (var targetProp in targetProps)
{
if (prop.Name == targetProp.Name)
{
targetProp.SetValue(targetItem, prop.GetValue(source));
//assign
}
}
}
return targetItem;
}
}
This is the link to my original answer.

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

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.

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