Validation error about Decimal data type in asp.net mvc - asp.net-mvc

I defined a data type decimal(18,10) for longitute and latitute in my database. But it always said "validation error" when I tried to input and submit my form.
I used LINQ to SQL. Is there some validation rules it generated for me otherwise why I can not input these two with something numbers like "2.34".
Thanks in advance
namespace Nerddinner.Models
{
interface IDinnerRepository
{
IQueryable<Dinner> FindAllDinners();
Dinner GetDinner(int id);
void AddDinner(Dinner dinner);
void UpdateDinner(Dinner dinner);
void DeleteDinner(Dinner dinner);
}
}
namespace Nerddinner.Models
{
public class sqlDinnerRepository: IDinnerRepository
{
dbDataContext db;
public sqlDinnerRepository()
{
db = new dbDataContext();
}
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(x => x.DinnerID == id);
}
public void AddDinner(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void UpdateDinner(Dinner dinner)
{
db.SubmitChanges();
}
public void DeleteDinner(Dinner dinner)
{
db.Dinners.DeleteOnSubmit(dinner);
}
}
}
namespace Nerddinner.Controllers
{
public class DinnerController : Controller
{
IDinnerRepository _repository;
public DinnerController()
{
_repository = new sqlDinnerRepository();
}
public DinnerController(IDinnerRepository repository)
{
_repository = repository;
}
//
// GET: /Dinner/
public ActionResult Index()
{
var dinners = _repository.FindAllDinners();
return View(dinners);
}
//
// GET: /Dinner/Details/5
public ActionResult Details(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// GET: /Dinner/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Dinner/Create
[HttpPost]
public ActionResult Create(Dinner dinner)
{
try
{
// TODO: Add insert logic here
_repository.AddDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// POST: /Dinner/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var db = new dbDataContext();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
try
{
// TODO: Add update logic here
UpdateModel(dinner, collection.ToValueProvider());
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// POST: /Dinner/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
var db = new dbDataContext();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
try
{
// TODO: Add delete logic here
_repository.DeleteDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
}
}
Thanks for helping me.

In ASP.NET MVC, You can use the DisplayFormatAttribute on your model property:
[DisplayFormat(DataFormatString = "{0:0.##}")]
public decimal decimalNumber { get; set; }
The above will output a number with up to 2 decimal places.
For more information visit: Custom Numeric Format Strings and Standard Numeric Format Strings
IN SQL SERVER:
*decimal(m,a)*: m is the number of total digits your decimal can have, while a is the max number of decimal points you can have.
so if you put PI into a Decimal(18,0) it will be recorded as 3
if you put PI into a decimal(18,2) it will be recorded as 3.14
if you put PI into Decimal(18,10) be recorded as 3.1415926535
I think my answer will help you. Correct me if I am wrong.

Related

How to load second partialview after success inserted in first partialview?

I have a view named Register.cshtml and 2 partialview named _AddUser.cshtml And _UserList.cshtml.
When I run the project shows register.cshtml and _AddUser.cshtml load in view. I want to load _UserList partialview after success inserted in _AddUser partialview.
DefaultController:
public class DefaultController : Controller
{
UserRepository UR = new UserRepository();
Automation_DBEntities database = new Automation_DBEntities();
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Users user, HttpPostedFileBase file)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
///////////////////SaveImage
if (file != null)
{
if (user.UserImage != "no-photo.jpg")
{
if (System.IO.File.Exists(Server.MapPath("/image/UserImage/" + user.UserImage)))
System.IO.File.Delete(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.UserImage = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
file.SaveAs(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.RegisterDate = DateTime.Now;
if (blUser.Add(user))
{
return PartialView("_UserList");//Inserted
}
else
{
}
}
else
{
}
}
[HttpGet]
public ActionResult AddUser()
{
return PartialView("~/Areas/Admin/Views/Shared/_AddUser.cshtml");
}
[HttpGet]
public ActionResult UserList()
{
IQueryable<AutomationSystem.Models.DomainModel.Users> list = UR.Select();
return PartialView("~/Areas/Admin/Views/Shared/_UserList.cshtml", list);
}

Get recent inserted Id and send in to another controllers view

EDITED:
I have Created CRUD Functions for each Modals and now i am trying to get recent Inserted Id and use it in different view.
Here is what I have tried so far
I have created 2 classes(Layer based) for CRUD function for each ContextEntities db to practice pure OOP recursive approach and following is the code.
1. Access Layer
ViolatorDB
public class ViolatorDB
{
private TPCAEntities db;
public ViolatorDB()
{
db = new TPCAEntities();
}
public IEnumerable<tbl_Violator> GetALL()
{
return db.tbl_Violator.ToList();
}
public tbl_Violator GetByID(int id)
{
return db.tbl_Violator.Find(id);
}
public void Insert(tbl_Violator Violator)
{
db.tbl_Violator.Add(Violator);
Save();
}
public void Delete(int id)
{
tbl_Violator Violator = db.tbl_Violator.Find(id);
db.tbl_Violator.Remove(Violator);
Save();
}
public void Update(tbl_Violator Violator)
{
db.Entry(Violator).State = EntityState.Modified;
Save();
}
public void Save()
{
db.SaveChanges();
}
}
2. Logic Layer
ViolatorBs
public class ViolatorBs
{
private ViolatorDB objDb;
public ViolatorBs()
{
objDb = new ViolatorDB();
}
public IEnumerable<tbl_Violator> GetALL()
{
return objDb.GetALL();
}
public tbl_Violator GetByID(int id)
{
return objDb.GetByID(id);
}
public void Insert(tbl_Violator Violator)
{
objDb.Insert(Violator);
}
public void Delete(int id)
{
objDb.Delete(id);
}
public void Update(tbl_Violator Vioaltor)
{
objDb.Update(Vioaltor);
}
}
And Finally using Logic Layer functions in presentation Layer.Here insertion is performed as:
public class CreateViolatorController : Controller
{
public TPCAEntities db = new TPCAEntities();
private ViolatorBs objBs;
public CreateViolatorController()
{
objBs = new ViolatorBs();
}
public ActionResult Index()
{
var voilator = new tbl_Violator();
voilator=db.tbl_Violator.Add(voilator);
ViewBag.id = voilator.VID;
return View();
}
[HttpPost]
public ActionResult Create(tbl_Violator Violator)
{
try
{
if (ModelState.IsValid)
{
objBs.Insert(Violator);
TempData["Msg"] = "Violator Created successfully";
return RedirectToAction("Index");
}
else
{
return View("Index");
}
}
catch (Exception ex)
{
TempData["Msg"] = "Failed..." + ex.Message + " " + ex.ToString();
return RedirectToAction("Index");
}
}
}
Now here is the main part how do i get perticuller inserted id in another controller named Dues while performing insertion ?
In sqlqery I would have used ##IDENTITY but in Entity Framework I'm not sure.
I'm new to mvc framework any suggestion or help is appreciated Thanks in Advance.
Once you save your db context the id is populated back to your entity by EF automatically.
for example.
using(var context = new DbContext())
{
var employee = new Employee(); //this has an id property
context.Employees.Add(employee);
context.SaveChanges();
var id = employee.id; // you will find the id here populated by EF
}
You dont need to add and save your table as you have done this already in your voilatorDB class just fetch the last id like following
var id = yourTableName.Id;
db.yourTableName.find(id);
Or you can simply write one line code to achive that using VoilatorBs class function
GetbyID(id);

How "Don't Repeat Yourself" in methods of a Controller in ASP.NET MVC?

within each methods of a controller , I have to execute a method.
public ActionResult Index1()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index1();
return View();
}
public ActionResult Index2()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index2();
return View();
}
public ActionResult Index3()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index3();
return View();
}
public ActionResult Index4()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index4();
return View();
}
Is there a smarter way than organize the code or I am forced to go against DRY concept?
I'd like not repeat the code for each method :
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Thanks to all.
Well, ASPNET has already the infrastructure for handling authorization so why not just use it?
Create a new attribute class, inherited from AuthorizeAttribute
Override the methods:
OnAuthorization: to perform your check
HandleUnauthorizedRequest: to decide whats the result view that the user will see.
Mark your controller methods with this attribute.
Your attribute may look like:
class MyCustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Do whatever you want here, for example
//filterContext.Result = new whatever() ;
base.HandleUnauthorizedRequest(filterContext);
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if ( /* the request does not pass your checks */ )
throw new UnauthorizedAccessException();
}
}
And your controller code will look like:
[MyCustomAuthorize]
public ActionResult Index1()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index2()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index3()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index4()
{
return View();
}
You can also check this post for a more clear example:
https://stackoverflow.com/a/5663518/1413973
You can refactor your controller like this:
public ActionResult Index1()
{
return AccessDeniedRedirect();
}
public ActionResult Index2()
{
return AccessDeniedRedirect();
}
public ActionResult Index3()
{
return AccessDeniedRedirect();
}
public ActionResult Index4()
{
return AccessDeniedRedirect();
}
private ActionResult AccessDeniedRedirect()
{
if (Checks(id, SessionManage.DataSession))
return RedirectToAction("AccesDiened");
return View();
}

Inconsistent accessibility: parameter type is less accessible

public class UserController : Controller
{
//
// GET: /User/
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User U)
{
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
dc.Users.Add(U);
dc.SaveChanges();
ModelState.Clear();
U = null;
ViewBag.Message = "Successfully register Done";
}
}
return View(U);
}
}
I suspect, but without the full error message giving us the type and location in the code it is something of a guess, that type User is protected or internal.

The resource cannot be found Error

This error comes to me.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Dinner
I searched but there is not suitable answers for me.
The spell of my controller is correct. I tried and checked many times.
I did not customize my rounting Globle.asax
I checked the "Web" tab under my project's properties, the "SpecificPage is tickled without any contents"
Everything is by default. Anyway here is the default code for rounting. Who knows why?Thanks
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Here is my Dinner controller
namespace NerdDinner.Controllers
{
public class DinnerController : Controller
{
IDinnerRepository _repository;
public DinnerController()
{
_repository = new sqlDinnerRepository();
}
public DinnerController(IDinnerRepository repository)
{
_repository = repository;
}
//
// GET: /Dinner/
public ActionResult Index()
{
var dinners = _repository.FindAllDinners();
return View(dinners);
}
//
// GET: /Dinner/Details/5
public ActionResult Details(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// GET: /Dinner/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Dinner/Create
[HttpPost]
public ActionResult Create(Dinner dinner)
{
try
{
// TODO: Add insert logic here
_repository.AddDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// POST: /Dinner/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var dinner = _repository.GetDinner(id);
try
{
// TODO: Add update logic here
UpdateModel(dinner, collection.ToValueProvider());
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// POST: /Dinner/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
var db = new dbDataContext();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
try
{
// TODO: Add delete logic here
_repository.DeleteDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
}
}
Here is IDinnerRepository interface
namespace NerdDinner.Models
{
interface IDinnerRepository
{
IQueryable<Dinner> FindAllDinners();
Dinner GetDinner(int id);
void AddDinner(Dinner dinner);
void UpdateDinner(Dinner dinner);
void DeleteDinner(Dinner dinner);
}
}
sqlDinnerRepository class implements IDinnerRepository interface
namespace NerdDinner.Models
{
public class sqlDinnerRepository
{
dbDataContext db;
public sqlDinnerRepository()
{
db = new dbDataContext();
}
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(x => x.DinnerID == id);
}
public void AddDinner(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void UpdateDinner(Dinner dinner)
{
db.SubmitChanges();
}
public void DeleteDinner(Dinner dinner)
{
db.Dinners.DeleteOnSubmit(dinner);
}
}
}
I type "http://localhost:52372/Dinner" in my browser.

Resources