MVC3 - Reading GET Variables Into Controller Action - asp.net-mvc

I have a controller action /Responses/Insert and want to be able to GET variables from URL and save them to my database.
The URL will look like this:
/Responses/Insert?pass=blah&msisdn=blah&sender=blah&message=blah&dca=blah&msg_id=blahsource_id=blah
Here is my model:
public class Response
{
public int ResponseId { get; set; }
public string msisdn { get; set; }
public string sender { get; set; }
public string message { get; set; }
public string dca { get; set; }
public string msg_id { get; set; }
public string source_id { get; set; }
}
Can anyone offer advice on how to code my controller action?
//
// GET: /Response/Insert
public ActionResult Insert()
{
return View();
}
Thanks very much!
Paul
EDIT 1 - SOLVED (Thanks LukLed)
public ActionResult Insert(Response response)
{
if (ModelState.IsValid)
{
responseRepository.InsertOrUpdate(response);
responseRepository.Save();
return RedirectToAction("Index");
}
else
{
return View();
}
}

Try this:
public ActionResult Insert(Response response)
{
return View();
}
Model binder will handle turning GET values into Response object.

Related

System.ArgumentNullException: Value cannot be null. Parameter name: entitySet?

When I tried to add data into the database this exception arise. I cant figure out where the problem exist. please help me to find out the where the problem is.
[Table("actors_tb")]
public class Actors
{
[Key]
public int id { get; set; }
public string name { get; set; }
public string sex { get; set; }
public DateTime dob { get; set; }
public string bio { get; set; }
}
This is my DbContext Class
public class CinemaDbContext:DbContext
{
public CinemaDbContext() : base("DefaultConnection")
{
}
public DbSet<Actors> actores { get; set; }
public DbSet<Producers> Producer { get; set; }
public DbSet<movie> movies { get; set; }
}
This is my controller
public ActionResult Actors()
{
return View();
}
[HttpPost]
public ActionResult Actors(Actors actors)
{
Db.actores.Add(actors);
Db.SaveChanges();
return View();
}

ASP:NET MVC Summary of a field as a validation for the field itself (Recursiveness)

I Have the following class in a model:
public partial class OrganizationUnit
{
public string code{ get; set; }
public int OrganizationCod { get; set; }
public string name { get; set; }
public string ParentUnitCode{ get; set; }
public int level{ get; set; }
public string author{ get; set; }
public System.DateTime CreateDtStmp{ get; set; }
public int Status { get; set; }
public decimal weighing { get; set; }
[ForeignKey("status")]
public virtual Status UnitStatus { get; set; }
public virtual Organization Organization { get; set; }
public virtual ICollection<OrganizationUnit> OrganizationUnit1{ get; set; }
[ForeignKey("ParentUnitCode")]
public virtual OrganizationUnit OrganizationUnit2{ get; set; }
public OrganizationUnit ()
{
CreateDtStmp= DateTime.Now;
author = HttpContext.Current.User.Identity.Name.Substring(4,HttpContext.Current.User.Identity.Name.Length - 4);
}
}
Before inserting a new record I need to validate sum(weighing) can not exceed 100 including the attempted new record, considering only the records with the same ParentUnit.
Can this be done in the model or should it be done in the controller?
this is the saving controller part (basically is what is autogenerated by VS),consider that the view will send the corresponding parameter to the method:
private SAIM_IPM_DVContext db = new SAIM_IPM_DVContext();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OrganizationUnit organizationunit)
{
if (ModelState.IsValid)
{
db.OrganizationUnit.Add(organizationunit);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(organizationunit);
}
If OrganizationUnit1 is the collection of all other units with the same ParentUnit, you can perform the check in the ViewModel by implementing IValidatableObject:
using System.ComponentModel.DataAnnotations;
public partial class OrganizationUnit : IValidatableObject {
/* properties etc... */
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (OrganizationUnit1.Sum(o => o.weighing) + this.weighing > 100.0) {
yield return new ValidationResult(
"Sum of weightings would exceed 100.",
new[] { "weighing" });
}
}
}
Note that this assumes that the weighing is posted back for all units in the OrganizationUnit1 collection (e.g. as hidden fields) so it is accessible when this check is performed by the MVC pipeline (this is done before your POST action will be hit).
If this check fails, ModelState.IsValid will be false in the controller.
If you have no access to the other units in the Viewmodel, you will have to fetch them from the DB in the controller and perform the check there.
After a while and tries I came up with this solution works perfect, however I am not sure is the best practice. This is on the controller class
public ActionResult Create(OrganizationUnit organizationunit)
{
decimal weighingsum= 0;
foreach (var val in db.OrganizationUnit.Where(t => t.ParentUnitCode== organizationunit.ParentUnitCode))
{
weighingsum+= val.weighing ;
}
weighingsum+= organizationunit.weighing ;
if (weighingsum > 100)
{
ModelState.AddModelError("", "Weighing sum can not exceed 100 for a Parent Unit");
}
else
{
if (ModelState.IsValid)
{
db.OrganizationUnit.Add(organizationunit);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(organizationunit);
}
should anyone comes up with a better solution, please do share I'll appreciate it.

No parameterless constructor defined for this object. (Debug never reaches any controller action?)

I hate these kind of errors.
I have an ASP.NET Core MVC form. When I submit the form I get the dreaded "No parameterless constructor defined for this object." error.
I can't seem to hit anything in the debugger to help me find where I have went wrong.
My controller:
using Brand.Extensions;
using Brand.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Brand.Controllers
{
public class ContentController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Upload()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upload(UploadedContentModel uploadedContentModel, FormCollection formCollection, IFormFileCollection uploadedFiles)
{
ContentExtensions contentExtensions = new ContentExtensions();
FileExtensions fileExtensions = new FileExtensions();
FileModel file = new FileModel();
file = fileExtensions.GetFileModel(uploadedFiles["File"]);
uploadedContentModel.File = fileExtensions.UploadFile(file).ID;
FileModel thumbnail = new FileModel();
thumbnail = fileExtensions.GetFileModel(uploadedFiles["Thumbnail"]);
uploadedContentModel.Thumbnail = fileExtensions.UploadFile(thumbnail).ID;
uploadedContentModel.ID = contentExtensions.UploadContent(uploadedContentModel).ID;
return View();
}
}
}
My model:
public class UploadedContentModel
{
public Guid ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Guid File { get; set; }
public Guid Thumbnail { get; set; }
public string ContentType { get; set; }
public string Solutions { get; set; }
public string Industries { get; set; }
public string AdditionalTags { get; set; }
public DateTime Publish { get; set; }
public DateTime Expire { get; set; }
public string AuthorizedRoles { get; set; }
public string Author { get; set; }
public DateTime Created { get; set; }
}

MVC Updates over values with NULL

This is probably very simple for most MVC programmers, so maybe you can help me out. I have a table called Images in the database with nine columns. On my UPDATE, I just have three I want to mess with (ImageName, ImagePath, CourseID). After I post back with UPDATE, it sets the other six columns to NULL. I'm not sure how to handle this in MVC.:
My ViewModel:
public class GalleryViewModel
{
public Image _image { get; set; }
}
My Model:
public partial class Image
{
public int ImageID { get; set; }
public string ImageName { get; set; }
public string ImagePath { get; set; }
public Nullable<int> CourseID { get; set; }
public string UserId { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public string ImageType { get; set; }
public string ImageSize { get; set; }
public string FriendlyName { get; set; }
public virtual Cours Cours { get; set; }
}
My Controller:
[HttpGet]
public ActionResult UploadImageEdit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var model = new GalleryViewModel
{
_image = db.Images.Find(id),
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImageEdit(GalleryViewModel galleryViewModel)
{
if (ModelState.IsValid)
{
db.Entry(galleryViewModel._image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("UploadImageIndex");
}
return View(galleryViewModel);
}
After reading other examples and becoming more familiar with ViewModel to controller, I got the UPDATE to work by doing the following:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImageEdit(int id, GalleryViewModel galleryViewModel)
{
if (ModelState.IsValid)
{
var imageContext = db.Images.Find(id);
imageContext.FriendlyName = galleryViewModel._image.FriendlyName;
db.Entry(imageContext).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("UploadImageIndex");
}
return View(galleryViewModel);
}
I hope this helps other folks out!

Value cannot be null

I have written ASP.NET MVC Code for CRUD but while Updating,Deleting and Details the page is throwing the error as value can not be null.my code is as follows:
public ActionResult Edit(int id=0)
{
var alb=db.Albums.FirstOrDefault(x=>x.AlbumId==id);
return View(alb);
}
public ActionResult Detail(int id=0)
{
var alb=db.Albums.Find(id);
return View(alb);
}
public ActionResult Delete(int id=0)
{
var album = db.Albums.Find(id);
return View(album);
}
and my Model is
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string AlbumTitle { get; set; }
public String Price { get; set; }
public String AlbumArtUrl { get; set; }
public Genre Genre { get; set; }
public Artist Artist { get; set; }
}
This is because the variable alb and album is showing me the null value its not getting any ID.
so suggest me on this.
This is because the variable alb and album is showing me the null
value its not getting any ID
If there is no record in your database then you should handle it gracefully in code. You should have something like:
var alb=db.Albums.FirstOrDefault(x=>x.AlbumId==id);
if (alb==null) {
// TempData, simplest way to give you an example
TempData["error_msg"] = "the record does not exists";
return RedirectToAction("index", "error");
}
return View(alb);
in your ErrorController
public ActionResult Index() {
ViewBag.ErrorMsg = TempData["error_msg"];
return View();
}
in the view (Index.cshtml) for your error controller
<h1>You have been, or trying to be, a naughty boy</h1>
<p>#ViewBag.ErrorMsg</p>
This is not the most elegant solution though but good enough to get you started. I think the most important part of my answer is not the code I gave you but the suggestion to handle that kind of situation (null values / missing or invalid records) in code.

Resources