I'm trying to create an ImagesController in MVC4 like this
But I keep getting this error.
Had no problem creating controller for PeopleController using this class
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual IEnumerable<Affair> Affairs { get; set; }
}
The problem is with your File property on the Image class. Because EntityFramework won't understand the type HttpPostedFileBase and can't store it in the DB and the controller generator is smart enough to check this. Altough the error message doesn't tell you what is the problem. To fix this you should rewrite your property to use a byte array:
public class Image
{
...
public byte[] File { get; set; }
}
And then the controller generation should work. And you can add your own image upload action, something like this:
[HttpPost]
public ActionResult Upload(Image image, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
db.Entry(image).State = EntityState.Modified;
image.File = new byte[file.ContentLength];
file.InputStream.Read(image.File, 0, file.ContentLength);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(image);
}
Related
I have a new Mvc Core application. I want to display a list if items from an sql view. Based on this article, I created a class corresponding to the sql view:
public class ItemsUsersAllocations
{
public int UserId { get; set; }
public int ItemId { get; set; }
...
}
Then I added the following code to the DbContext:
public virtual DbQuery<ItemsUsersAllocations> ItemsUsersAllocations { get; set; }
And the following to OnModelCreating() of the DbContext:
modelBuilder.Query <ItemsUsersAllocations>().ToView("vw_UsersAllocations");
I have the following simple action method in the controller before adding any viewmodel:
public IActionResult Index()
{
return View();
}
And now I tried to auto-generate the Index view. But got an error message:
How can I solve this?
after looking for an answer in the already existing questions, I am still a little confused as how I should proceed. I am new to the MVC 3 framework, so if I come off sounding like a dope, I appologize!!
Ok, so I created a MVC 3 internet application, created 3 new Users administrator, user1, and user2. I have created a new model, and controller for my "Posts" I am able to add, edit and delete the items. I currently have a column called UserID in my posts table. I would like this to be automagically populated with the current UsersID. I think I would define this in the controller like this:
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
public int User = System.Web.Security.Membership.GetUser(id);
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
Inside the model, this is what I currently have:
public class Post
{
public int PostID { get; set; }
public int UserID { get; set; }
public string PostTitle { get; set; }
public int PostType { get; set; }
public string PostBody { get; set; }
public string PostBlogTitle { get; set; }
public string PostBlogURL { get; set; }
public string PostCategory { get; set; }
public string PostSEO { get; set; }
public int PostStatus { get; set; }
}
public class PostDBContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
I would like to replace public int UserID { get; set; } with my newly defined variable in the controller, but not sure where/how to add it.
Not sure I'm clear on what you're trying to achieve. Are you just trying to assign the current user to the model, save it and then pass it back to the view?
If so you can just do this:
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
// Note: I'm assuming this actually works/returns an int
public int User = System.Web.Security.Membership.GetUser(id);
post.UserID = User;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
I'm building an MVC 3 website. I have a model looking like this:
public class Survey
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime DateStart { get; set; }
public DateTime DateEnd { get; set; }
// Not in view
public DateTime DateCreated { get; set; }
// Not in view
public DateTime DateModified { get; set; }
}
Based on this I also have a View Model to edit the survey information:
public class SurveyEditViewModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime DateStart { get; set; }
public DateTime DateEnd { get; set; }
}
When the user finishes editing I would like to persist the changes. Here's my controller post action:
[HttpPost]
public ActionResult Edit(SurveyEditViewModel model)
{
// Map the view model to a domain model using AutoMapper
Survey survey = Mapper.Map<SurveyEditViewModel, Survey>(model);
// Update the changes
_repository.Update(survey);
// Return to the overview page
return RedirectToAction("Index");
}
In my repository (it's a generic one for now) I have the following code:
public void Update(E entity)
{
using (ABCDataContext context = new ABCDataContext())
{
context.Entry(entity).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
}
When this executes I get the following error: "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."
I guess this was to be expected. Mapping from the view model to the model doesn't give me a complete Survey object.
I could modify my controller to look like this. And then it works:
[HttpPost]
public ActionResult Edit(SurveyEditViewModel model)
{
// Map the model to a real survey
survey = _repository.Find(model.Id);
survey.Name = model.Name;
survey.Description = model.Description;
survey.DateStart = model.DateStart;
survey.DateEnd = model.DateEnd;
// Update the changes
_repository.Update(survey);
// Return to the overview page
return RedirectToAction("Index");
}
But I was wondering if a better way is available?
[HttpPost]
public ActionResult Edit(SurveyEditViewModel model)
{
// Fetch the domain model to update
var survey = _repository.Find(model.Id);
// Map only the properties that are present in the view model
// and keep the other domain properties intact
Mapper.Map<SurveyEditViewModel, Survey>(model, survey);
// Update the changes
_repository.Update(survey);
// Return to the overview page
return RedirectToAction("Index");
}
I had a view model in that viewmodel i created two different instances using same model like this:
public ClaimViewModel()
{
engineClaim = new ClaimModel();
boatClaim = new ClaimModel();
}
public ClaimModel engineClaim { get; set; }
public ClaimModel boatClaim { get; set; }
I had properties in ClaimModel like this:
[Required]
public string Complaint { get; set; }
[RequiredIf("isEngineClaim", true , ErrorMessage = "Required")]
public string Cause { get; set; }
[Required]
public string Correction { get; set; }
public bool isEngineClaim { get; set; }
And in controller i am loading the index page like this
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
ClaimViewModel claim = new ClaimViewModel();
claim.engineClaim = new Models.ClaimModel();
claim.engineClaim.isEngineClaim = true;
claim.boatClaim = new Models.ClaimModel();
claim.boatClaim.isEngineClaim = false;
return View("Index", claim);
}
Now my problem is the requiredif validation is not working though the 'isEngineClaim' property is different for two instances. I am following this link
And moreover i had placed the hidden field of 'isEngineClaim' in my view also. But the requiredifvalidation is not working can anyone suggest me the solution.
I have a class, which has 8 props / 8 columns in DB. But on a Edit page, i dont want to show the AddedDate or UserID field, since i dont want user to change it.
public class Voucher
{
public int ID { get; set; }
public string Title { get; set; }
public string SiteName { get; set; }
public string DealURL { get; set; }
public DateTime AddedDate { get; set; }
public DateTime? ExpirationDate { get; set; }
public string VoucherFileURL { get; set; }
public Guid UserID { get; set; }
}
Here is what I have for Edit controller:
// POST: /Voucher/Edit/5
[HttpPost]
public ActionResult Edit(Voucher voucher)
{
if (ModelState.IsValid)
{
string[] excludeProperties = { "AddedDate", "UserID" };
UpdateModel(ModelState, "", null, excludeProperties);
db.Entry(voucher).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(voucher);
}
On Edit page, once i click on submit, i got the following error: System.Data.SqlServerCe.SqlCeException: An overflow occurred while converting to datetime.
Seems like the AddedDate didn't get excluded from the view model and triggered the error.
Would you please let me know how to fix it? Thanks!
public ActionResult Edit([Bind(Exclude = "AddedDate")]Voucher voucher)
no luck either
You are still passing in Voucher which could contain that field in it. I'm not sure what you are trying to accomplish with the UpdateModel here if you are already passing in a Voucher object?
Pass in Voucher, set it to modified and save it. If you want to use whats in the database then you'll have to
Load the object from the database
UpdateModel and exclude the properties
Save your entity.
You could simply use a View Model and post that.
public class Voucher
{
public int ID { get; set; }
public string Title { get; set; }
public string SiteName { get; set; }
public string DealURL { get; set; }
public DateTime? ExpirationDate { get; set; }
public string VoucherFileURL { get; set; }
public Guid UserID { get; set; }
}
and then load up your object from the db":
var voucher = db.Vouchers.Where(o=>o.ID==voucherViewModel.Id);
//manually copy the fields here then save it
//copy
db.SaveChanges();