Get Id of inserted data (ASP.NET) - asp.net

I have code in controller that write data from View to table
Here is code
[HttpGet]
public ActionResult WelcomeScreen()
{
// Формируем список команд для передачи в представление
SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
ViewBag.Teams = teams;
SelectList teams2 = new SelectList(db.Companies, "CompanyID", "CompanyName");
ViewBag.Teams2 = teams2;
return View();
}
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
int id = interview.Interview_Id;
return RedirectToAction("Index", "Questions");
}
Here is model
[Key]
public int Interview_Id { get; set; }
public string Greeting { get; set; }
public string Detail { get; set; }
public Nullable<int> VacancyId { get; set; }
public virtual Vacancy Vacancy { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Interwier> Interwiers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<InvitationMail> InvitationMails { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MassLink> MassLinks { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<QuestionBlock> QuestionBlocks { get; set; }
}
I need to have Interview_Id
I try to make it like this, but it not works int id = interview.Interview_Id;
How I can write id to variable?

If I understood your question right. You might have something like this.
public DbSet<Interview> Interviews {get; set;}
Rename Interview_Id to simply Id or InterviewId (no underscore).
public class Interview
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int InterviewId { get; set;}
// other properties
}
DAL Method.
public int Add(Interview inteview)
{
using(DbContext entities = new DbContext()
{
entities.Interviews.Add(interview);
entities.SaveChanges();
var id = interview.InterviewId;
return id;
}
}
From your Controller.
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
Dal dalObj = new Dal();
var inteviewId = dal.Add(interview);
//use this id
}
Hope this helps.

You can try this.
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
int id = db.Interview.Max(x=>x.Interview_Id);
return RedirectToAction("Index", "Questions");
}

check you dbml
make sure you have this attribute set correctly
AutoSync=AutoSync.OnInsert
the full attribute usually like this
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]

Related

Delete in cascade

I'm new to asp.net and mvc.
I have a class AsyApp
public class AsyApp
{
[Key]
public int AsyAppId { get; set; }
[DisplayName("Nom")]
public string Name { get; set; }
public virtual ICollection<Scene> Scenes { get; set; }
}
It has a collection of scenes
public class Scene
{
[Key]
[Required]
public int SceneId { get; set; }
[ForeignKey("AsyApp")]
public int AsyAppId { get; set; }
[Required]
public virtual AsyApp AsyApp { get; set; }
[ForeignKey("Name")]
public int NameId { get; set; }
[DisplayName("Nom")]
public virtual Translation Name { get; set; }
public int Order { get; set; }
}
And the Scene has a property Name from a class Translation
public class Translation
{
[Key]
[Required]
public int TranslationId { get; set; }
public string Fr { get; set; }
public string En { get; set; }
}
Here is my issue.
I will use the class Translation to handle language for every single string in my application. I could be in any other classes
I would like that when I delete an application, it delete the appropriate scenes and localisations
Here is my code for deleting an app
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AsyApp asyApp = db.AsyApps.Find(id);
if (asyApp == null)
{
return HttpNotFound();
}
db.AsyApps.Remove(asyApp);
db.SaveChanges();
return RedirectToAction("Index");
}
The scenes seams to be deleted automaticaly but not the localisations associated with them...
Hope you can help me
Thanks a lot
look at this link:
https://msdn.microsoft.com/en-us/data/jj591620.aspx#CascadeDelete
you can enable cascade delete using Fluent API.

How to make single view using viewmodel in asp.net mvc 4?

I have different models Image,Page & PageCategories
public class Image
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
}
public class Page
{
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public virtual PageCategory PageCategory { get; set; }
}
public class PageCategory
{
public int PageCategoryId { get; set; }
public string CategoryName { get; set;
public virtual ICollection<Page> Pages { get; set; }
}
DBContext Class is
class DemoContext:DbContext
{
public DbSet<PageCategory> PageCategories { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
I am wondering how to get all the model data to the home page using ViewModel.
For Ex.:
How to get image list and Page list in home page from multiple models?
You may want something like this :
viewModel :
//Create a viewModel with all the properties that you need
public class ViewModel
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public string CategoryName { get; set; }
}
Controller :
...
using (DemoContext db = new DemoContext()){
List<ImagePageViewModel> viewData = (from p in db.Page
join pc from db.PageCategory on p.PageCategoryId equals pc.PageCategoryId
select new ViewModel(){
PageTitle=p.PageTitle,
CategoryName = pc.CategoryName
//... set every property you want
})
}
return View(viewData );
note: I didn't add Image to the query because there is no explicit relation
between Image and the others table so i let you do it.
Create another class and define all above three into it. like below
public class MyView
{
public List<Image> Images { get; set; }
public List<Page> Pages { get; set; }
public List<PageCategory> PageCategories { get; set; }
}
Controller Action:-
public ActionResult Index()
{
MyView myView = // Get it using your logic
return View(myView);
}
finally got my answer:
public class ViewModelDemo
{
public IEnumerable<Image> images { get; set; }
public IEnumerable<Pages> pages { get; set; }
public IEnumerable<PageCategory> pagecategories { get; set; }
}
Then in HomeController
private DemoContext db=new DemoContext();
public ActionResult Index()
{
ViewModelDemo vm = new ViewModelDemo();
vm.images = db.Images.ToList();
vm.pages=db.Pagess.ToList();
vm.pagecategories=db.PageCategories.ToList();
return View(vm);
}

How to use mutiple models for one dbset

NET MVC expetrts!
I'm new in asp.NET MVC 4, so I got a simple problem not to know how to solve!
so this is my NotActivatedUsers model :
public class NotActivatedUser
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
[DefaultValue(false)]
public bool isActive { get; set; }
[Required, DataType(DataType.EmailAddress)]
public string email { get; set; }
[Required]
public string activeCode { get; set; }
public DateTime createDate { get; set; }
}
and here is my SignUp model :
public class SignUpModel
{
[Key]
public int id { get; set; }
[EmailAddress(ErrorMessage = "Invalid Email!")]
public string email { get; set; }
}
and this in my dbset:
public class Context : DbContext
{
public DbSet<NotActivatedUser> notActivatedUser { get; set; }
}
My problem is " How to use my SignUp model to insert into NotActivatedUsers Dbset?
I tried this :
public class AccountController : Controller
{
private Context db = new Context();
[HttpPost]
[AllowAnonymous]
public ActionResult SignUp(SignUpModel signUpModel)
{
if (ModelState.IsValid)
{
db.notActivatedUser.Add(signUpModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(signUpModel);
}
[AllowAnonymous]
public ActionResult SignUp()
{
return View();
}
}

MVC 5 Multiple Models in a Single View

Could somebody please provide an example of how to combine two models within one view?
Currently I have a page called RecordCard which contains:
#model IEnumerable<WebApplication1.Models.Weight>
This is provided by the following code in the AccountController:
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
return View(weightModel);
}
The RecordCard page also contains a form which is bound to the following class:
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
However, these are two individual models with different purposes, so how do I combine to a single model that contains an IEnumerable list and set of form elements that will ultimately post to the AccountController correctly to add a record to the database using the following code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(Weight Model)
{
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return View(Model);
}
I have included the Weight class below:
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
Also here is the WebApplication1Entities class which declares the Weight table as Weights:
public partial class WebApplication1Entities : DbContext
{
public WebApplication1Entities()
: base("name=WebApplication1Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Weight> Weights { get; set; }
}
Please explain what needs to be modified and how, no matter what I try to read, follow and implement, I seem to be missing something.
Any help would be much appreciated :-)
I would say this is good example of using ViewModel here. I would suggest something like -
Create ViewModel with the composition of the two classes
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
....
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
.....
public class WeightViewModel
{
public IList<AddWeightModel> AddWeightModel { get; set; }
public Weight Weight { get; set; }
}
Then change your view to accept the view models -
#model WeightViewModel
Finally modify your controller to cope with the change -
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
var viewModel = new WeightViewModel
{
Weight = weightModel,
AddWeightModel = new List<AddWeightModel>(){}
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(WeightViewModel viewModel)
{
Weight Model = viewModel.Weight;
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return RedirectToAction("RecordCard");
}
I've tackled this before, can came to an elegant solution.
First, you'd want to setup your main classes to send, as well as a 'holder' class to store them to eventually send to a view.
As you probably found out, this is because a view can't have multiple models sent to it.
public class WebsiteTheme
{
public string Color { get;set; }
public string Title { get;set; }
public WebsiteTheme() {
Color = "blue";
Title = "test website";
}
}
public class User
{
public string Name { get;set; }
public string Gender { get;set; }
public User() {
Name = "Anonymous";
Gender = "Unspecified";
}
}
public class ToPage
{
public WebsiteTheme WebsiteTheme{ get; set; }
public User User { get; set; }
public ToPage() {
websiteTheme = new WebsiteTheme();
user = new User();
}
}
This will allow you to send any amount of classes to your page.
Then, in your controller, you'd want to populate those classes. Make sure to initialise them all first, then set the populated classes to your holder class.
WebsiteTheme websiteTheme = new WebsiteTheme();
websiteTheme.Color = "orange";
User user = new User();
user.Name = "Darren";
ToPage toPage = new ToPage();
toPage.User = user;
toPage.WebsiteTheme = websiteTheme;
return View(toPage);
In your view, you'd call them in any way you want to. But make sure to use HolderModel.SpecifiedModel in every case.
#model WebApplication1.Models.ToPage
#Html.DisplayFor(model => model.User.Name)
I did a compound model like this:
public class CompoundModel
{
public SearchModel SearchModel { get; set; }
public QueryResultRow ResultModel { get; set; }
}
public class QueryResultRow
{
[DisplayName("Id")]
public long id { get; set; }
[DisplayName("Importdatum")]
public System.DateTime importdate { get; set; }
[DisplayName("Mandant")]
public int indexBMClient { get; set; }
}
public class SearchModel
{
[Required]
[DataType(DataType.Date)]
[Display(Name = "Zeitraum von")]
public DateTime dateFrom { get; set; }
[Display(Name = "Terminal-ID")]
public string tid { get; set; }
[Display(Name = "Belegnummer")]
public string receiptnumber { get; set; }
}
In the view header:
#model MyProject_aspmvc.Models.CompoundModel
And get data access from the SearchModel, for example:
model => model.SearchModel.tid
and data access from the ResultModel, for example:
model => model.ResultModel.importdate

Help understanding the basics of AutoMapper

So I have this two classes:
public class PhysicalTest
{
public int ID { get; set; }
public DateTime CreationDate { get; set; }
public int Weight { get; set; }
public int Height { get; set; }
public int Systolic { get; set; }
public int Diastolic { get; set; }
public int Pulse { get; set; }
}
public class PhysicalTestFormViewModel
{
public int ID { get; set; }
public DateTime CreationDate { get; set; }
[Required]
public int Weight { get; set; }
[Required]
public int Height { get; set; }
public int Systolic { get; set; }
public int Diastolic { get; set; }
public int Pulse { get; set; }
}
This is my AutoMapper configuration
Mapper.CreateMap<PhysicalTestFormViewModel, PhysicalTest>();
When I do this it works just fine
[HttpPost]
public ActionResult Create(int ehrId, PhysicalTestFormViewModel physicaltestvm)
{
EHR ehr = ehrRepository.Find(ehrId);
if (ehr.UserName != User.Identity.Name)
return View("Invalid Owner");
if (ModelState.IsValid)
{
PhysicalTest physicalTest= new PhysicalTest();
Mapper.Map(physicaltestvm, physicalTest);
physicalTest.PerformedBy = "Yo";
physicalTest.CreationDate = DateTime.Now;
ehr.PhysicalTests.Add(physicalTest);
ehrRepository.Save();
return RedirectToAction("Index");
}
else
{
return View(physicaltestvm);
}
}
But when I do this I get an error
Trying to map Summumnet.PhysicalTest
to
Summumnet.ViewModels.PhysicalTestFormViewModel.
Missing type map configuration or
unsupported mapping. Exception of type
'AutoMapper.AutoMapperMappingException'
was thrown.
public ActionResult Edit(int ehrId, int id)
{
EHR ehr = ehrRepository.Find(ehrId);
if (ehr.UserName != User.Identity.Name)
return View("Invalid Owner");
var physicalTest = ehr.PhysicalTests.Where(test => test.ID == id).Single();
PhysicalTestFormViewModel physicaltestvm = new PhysicalTestFormViewModel();
Mapper.Map(physicalTest, physicaltestvm);
return View(physicaltestvm);
}
In the scenario where the error is thrown I simply want to construct an ViewModel to display an Edit form.... what is the standard way of doing this?
You have only defined a mapping from PhysicalTestFormViewModel to PhysicalTest:
Mapper.CreateMap<PhysicalTestFormViewModel, PhysicalTest>();
You also need the opposite one:
Mapper.CreateMap<PhysicalTest, PhysicalTestFormViewModel>();
See this related SO question and answers.
you may do dynamic mapping where you dont have to create any maps
public ActionResult (PhysicalTestFormViewModel ptvm)
{
//other to wrote codes
EHR ehr = ehrRepository.Find(ehrId);
AutoMapper.Mapper.DynamicMap<PhysicalTestFormViewModel, PhysicalTest>(ptvm, ehr);
db.SaveChanges();
}

Resources