I'm new to asp.net mvc and the entity framework and i'm trying to make a dropdownlist with data out of my database. I have the following:
Controler:
//
// GET: /StoreEditor/Edit/(ID)
public ActionResult Edit(int id)
{
StoreEditorViewModel data = new StoreEditorViewModel(id);
return View(data);
}
ViewModel:
public StoreEditorViewModel(int id)
{
using (MvcTicketsEntities storeDB = new MvcTicketsEntities())
{
details = (from t in storeDB.Tickets.Include("Artists").Include("Genres")
where t.TicketId == id
select t).FirstOrDefault();
}
}
Now i get get all my labels and editors in de view. But how do i make a dropdownlist with all the names in the database table GENRES in the field NAME.
The table GENRES has 2 fields GenreId and Name.
Please refer to the below link:
http://codeclimber.net.nz/archive/2009/08/10/how-to-create-a-dropdownlist-with-asp.net-mvc.aspx
This explains quite well, how to approach it.
Basically, you would need to create List<SelectListItem> object and supply it to the dropdown list.
Thanks
Related
I have 3 custom objects with a Master-Detail Relationship and Lookup Relationship.
CustomA__c (related CustomB__c) <-> CustomB__c <-> CustomC_c (related CustomB_cc)
I´ve built a Visualforce page with HTML table to replicate a PDF document and a Custom Controller Extension, so far so good.
But I´m just a beginner with apex coding.
The problem is that I need to replicate the document as it is, when there are no related records for CustomA__c or less then 5, it should still show the full table (the empty rows). Max. rows/related records on the document is 5, no second page needed.
Currently I´m trying to accomplisch that by using apex:variable and apex:repeat as I´ve seen some examples, but perhaps there is also another solution. For the Visualforce page I already wrote the code for the rows with data and another apeax:repeat for the empty rows.
But I´m really strugling with the controller, i know i need to iterate over the list, the code that i already wrote is also put together out of examples as i just don´t understand it yet good enough.
Any help would be appreciated! Thanks, Josip
public with sharing class CustomAController {
public CustomA__c customa{get; set;}
public CustomA__c ca{get; set;}
public CustomAController (ApexPages.StandardController controller) {
ca = (CustomA__c )controller.getRecord();
customa= [SELECT Id, Name FROM CustomA__c WHERE Id = :ApexPages.currentPage().getParameters().get('Id')];
}
public List<CustomB__c > getrelatedCustomB() {
List <CustomB__c > cbList = New List<CustomB__c >(5);
for(CustomA__c acc:[SELECT Id, Name, (SELECT Id, Name, ... , CustomCfield__r.Name FROM CustomBs__r ORDER BY Name LIMIT 5) FROM CustomA__c WHERE Id = :customa.Id]){
for(CustomB__c cb:acc.CustomBs__r)
cbList.add(cb);
}
return cbList;
}
}
You can dramatically simplify your code by writing a direct query on the child object instead of a parent-child SOQL query.
public List<CustomB__c > getrelatedCustomB() {
return [SELECT Id, Name, ... , CustomCfield__r.Name
FROM CustomB__c
WHERE CustomA__c = :customA.Id
ORDER BY Name
LIMIT 5];
}
There's no need to iterate in Apex here.
I have a non nullable fields in a table with default values set already in the property "Default Value or Binding" in SSMS. I linked this table in an ASP.Net mvc application. When I created the view and when running the create view, it still asking me to enter the required fields for the non nullable fields even though i assigned a default value for them.
After this I removed the line:
#Html.ValidationMessageFor(model => model.position, "", new { #class = "text-danger" })
which is bellow each
#Html.EditorFor statement, but this time it post me back to the same page with no changes in the database.
How can I get rid of the message in the required fields as I have already default value for them?
Simply you can create a constructor in your model. It will initialize default values once new instance is created. If user provides that fields, then it will be overridden. If no, value from constructor will be passed to EF.
What you are trying to do now, won't work according to specifications: https://msdn.microsoft.com/en-us/library/ms187872.aspx
Here you can see how to achieve what you want, considering that this field will always be generate in database.
This is one of the many reasons not to use entity models as viewmodels. MVC doesn't care that the required field has a default value, that information is database-related and not related to input validation.
Introduce a viewmodel where those properties are not required, and map the posted viewmodel to your entity model.
So, given an entity model that looks like this:
public class SomeEntity
{
// this property is not-nullable in the database
[Required]
public string SomeRequiredDatabaseField { get; set; }
}
Because the SomeRequiredDatabaseField is NOT NULL, it is annotated as such by Entity Framework, even if it has a default value. MVC will pick up this annotation, and consider the model not valid when the property has no value.
Now if you introduce a viewmodel, you can tell MVC that this property is not required:
public class SomeViewModel
{
// Not required
public string SomeRequiredDatabaseField { get; set; }
}
Now in your controller, you map the viewmodel to the entity model (preferably using AutoMapper):
public ActionResult Post(SomeViewModel model)
{
if (ModelState.IsValid)
{
var entityToSave = new SomeEntity
{
SomeRequiredDatabaseField = model.SomeRequiredDatabaseField
};
db.SomeEntity.Add(entityToSave);
}
// ...
}
I have a method that performs an insert into a table using Entity Framework 6. The table has an ID field that is populated automatically when it is written to SQL Server. I would like the method to return all of the data that was previously in the ModelState as well as the new record. When I run this code, I get everything except for the new record's ID, which comes back as a 0.
How can I rework this so it returns the new ID as well as the rest of the data from ModelState?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, Book book)
{
if (bookViewModel != null && ModelState.IsValid)
{
MyRepository db = new MyRepository();
db.Books.Add(book);
db.SaveChanges();
}
return Json(ModelState.ToDataSourceResult());
}
Function Add return from db result of adding with correct id parameter.
Try this:
book = db.Book.Add(book);
It give you what you want.
If you want return model and modelstate use this:
return Json(new[] { book }.ToDataSourceResult(request, ModelState);
My WPF desktop-based application uses ADO.Net Entity Framework in order to connect to SQL Server database. In one of the windows I have a DataGrid with all data from tbl_users, when user selects one of the rows (records) and clicks on Edit, application opens a new window with form, that includes all data that user can edit/update.
How to save changes (update/edit) of one of the table's values to database via ADO.NET Entity Framework?
Here are some code snippets that help understand a situation:
1 - Edit window constructor
public object objToBeEdited;
public WinWorkers_EditWorker(tbl_users userToBeEdited){
this.Title = Glidus.Properties.Resources.WinWorkers_EditWorker_WinName + Glidus.Properties.Resources.WinApp_WinName;
}
2 - Method Update, that doesn't work
//assume inputted values to new object
tbl_users newUser = new tbl_users() {
userName = this.WinWorkers_AddEditWorkers_Form_UserName.Text,
userPassword = this.WinWorkers_AddEditWorkers_Form_Password.Text,
userAccessLevel = this.WinWorkers_AddEditWorkers_Form_UserAccessLevel.Text
};
//default minimal password length is 4
if (App.IsInputValueMinLenOK(newUser.userPassword, 4)) {
EntityKey key = App.glidusContext.CreateEntityKey("tbl_users", objToBeEdited);
if (App.glidusContext.TryGetObjectByKey(key, out objToBeEdited)) {
App.glidusContext.ApplyCurrentValues<tbl_users>(key.EntitySetName, newUser);
}
try {
App.glidusContext.SaveChanges();
}
catch (Exception ex) {
App.UnitedHandleException(ex);
}
}
Please, help me, how to implement update ADO.NET record from the database. For example, in my table there is James Bond 007, after editing page (clicking in submit page) I see Austin Powers 008.
To edit or update you can use stub entities
Category category = new Category { ID = 5};
Context.AttachTo(“Categories”,category);
Product product = new Product {
Name = “Bovril”,
Category = category
};
Context.AddToProducts(product);
Context.SaveChanges();
I need some help. What I am trying to do is show the locations of a device belonging to a specific project.
On the projects page I have a button which goes to the google map. For projects I have a Projects model and controller.
I've got 2 tables, a table containing the location of a device and a project table. I want to display all device locations belonging to a project on a google map. The google maps part is working and I managed to show all device locations on 1 map, only problem is I can't seem to link the devices to the project. I need some help on how to achieve this.
In the Location table ive got a foreign key to the projects table. this is a many-to-onerelation. A project can have multiple devices, but a device can only be linked to 1 project. I have defined the relation as follows in the location model:
[BelongsTo("ProjectID")]
public Project project
{
get { return _project; }
set { _project = value; }
}
In the Location controller I use the following code(theres more but for the moment its not relevant):
public ActionResult Index()
{
return View(DeviceLocation.FindAll());
}
This simply lists all locations in the location table. What I need is to list all locations where the ProjectID = the ID of the projects table. I'm coming from PHP/MYSQL and there you would simply join the 2 tables. How do I achieve this with asp mvc?
You should read up on LINQ and how to use it to query your data.
Something like this should help:
public ActionResult Index()
{
return View(DeviceLocation.Where(d=> d.ProjectId == myProjectId));
}