This is the properties to validate. (Code from my cshtml.cs (Razor))
[BindProperty]
public TMedProductStorageLocation TMedProductStorageLocation { get; set; }
[BindProperty]
public IList<TStorageLocation> TStorageLocations { get; set; }
[BindProperty]
public int SelectedStorageLocationId { get; set; }
[BindProperty]
public TMedProduct SelectedProduct { get; set; }
[BindProperty]
public int RelocateAmount { get; set; }
These are the properties I want to Validate. But It also Validates:
public class TSubstanceGroup
{
public TSubstanceGroup()
{
TMedProducts = new HashSet<TMedProduct>();
}
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Geben Sie eine Bezeichnung ein.")]
public string Name { get; set; }
public ICollection<TMedProduct> TMedProducts { get; set; }
}
because this is a related table to TMedProduct.
How can I avoid validation for related tables?
Not sure what is your razor pages design,but you need to know that ModelState will validate all the models you define in razor pages backend not due to you have relationship between models:
public class PrivacyModel : PageModel
{
[BindProperty]
public TSubstanceGroup TSubstanceGroup { get; set; }
[BindProperty]
public TMedProduct SelectedProduct { get; set; }
[BindProperty]
public TMedProductStorageLocation TMedProductStorageLocation { get; set; }
[BindProperty]
public IList<TStorageLocation> TStorageLocations { get; set; }
[BindProperty]
public int SelectedStorageLocationId { get; set; }
[BindProperty]
public int RelocateAmount { get; set; }
public IActionResult OnPost()
{
//...
}
public void OnGet()
{
//..
}
}
To avoid validation for related tables,you could remove the validation with the key:
public IActionResult OnPost()
{
ModelState.Remove("KeyName");
if(ModelState.IsValid)
{
//...
}
return Page();
}
For how to know the key name,you could check in the ModelState:
Related
I'm working on an web API, where it needs to receive the multi-part form data with in a model. As of now it's not receiving the request and showing the Bad request When I tried from the Postman.
My model :
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormCollection> invoice_file { get;set;}
[FromForm(Name = "other_files")]
public List<IFormCollection> other_files { get; set; }
}
In the above class/model "invoice_file" and "other_files" can have multiple file uploads so I made it List.
My Action Method :
[HttpPost]
[Route("CreateInvoice")]
public IActionResult CreateInvoice([FromForm]InvoiceDetails idobj )
{
//var modelData = Request.Form["invoice_file"];
Response resobj = new Response();
try
{
if (idobj.invoice_file.Count > 0)
{
resobj = _dataContext.AddInvoice(idobj);
if (resobj.flag == true)
{
Upload(idobj);
}
}
else
{
resobj.flag = false;
resobj.message = "please upload atleast one invioce file";
}
}
catch (Exception ex)
{
}
return Ok(resobj);
}
How can I make the action method or model, in such a way that user can upload the model with multiple files to the properties other_files & invoice_file.
Reference of postman Image
As CodeCaster says,add Content-Type:multipart/form-data; and change List<IFormCollection> to List<IFormFile>.It is not changing the whole model to List.So you can also retrieve other information which exists in your model with idobj.xxx.Change
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormCollection> invoice_file { get;set;}
[FromForm(Name = "other_files")]
public List<IFormCollection> other_files { get; set; }
}
to
public class InvoiceDetails
{
public int? po_id { get; set; }
public DateTime created_date { get; set; }
public string grn_status { get; set; }
public int utilization_amount { get; set; }
public int currency_id { get; set; }
public string currency_code { get; set; }
public string currency_symbol { get; set; }
[FromForm(Name = "invoice_file")]
public List<IFormFile> invoice_file { get; set; }
[FromForm(Name = "other_files")]
public List<IFormFile> other_files { get; set; }
}
result:
IFormCollection is used to retrieve all the values from posted form data.refer to the official document.
If you want to use c,you can try to use it,you can do like this
public IActionResult CreateInvoice([FromForm]IFormCollection idobj)
and you need to get the data you want to foreach keys of IFormCollection,so public List<IFormCollection> invoice_file { get;set;} is better than use IFormCollection.
I'm trying to work my way through a Dot Net Core MVC project, but I am facing a problem I couldn't solve.
And honestly, I didn't know what to search for.
The project is a simple vehicle registry,
Each vehicle has a Make, a Model, a some Features.
Here are the domain models:
public class Make
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Model> Models { get; set; }
public Make()
{
Models=new Collection<Model>();
}
}
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public Make Make { get; set; }
public int MakeId { get; set; }
public Model()
{
Make=new Make();
}
}
public class Feature
{
public int Id { get; set; }
public string Name { get; set; }
}
[Table(name:"VehicleFeatures")]
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId { get; set; }
public Feature Feature { get; set; }
public Vehicle Vehicle { get; set; }
public VehicleFeature()
{
Feature=new Feature();
Vehicle=new Vehicle();
}
}
public class Vehicle
{
public int Id { get; set; }
public Model Model { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ModelId { get; set; }
public ICollection<VehicleFeature> VehicleFeatures { get; set; }
public string ContactName { get; set; }
public string ContactPhone { get; set; }
public string ContactEmail { get; set; }
public DateTime LastUpdate { get; set; }
public bool IsRegistered { get; set; }
public Vehicle()
{
Model=new Model();
VehicleFeatures=new Collection<VehicleFeature>();
}
}
The problem is that when I send the following request to the corresponding controller, EF is replacing the provided value with a new incremental value.
The request I send:
{
"ModelId":10,
"VehicleFeatures":[
{"featureId":45},
{"featureId":46}
],
"ContactName":"Alice",
"ContactPhone":"1234",
"ContactEmail":"Alice#local",
"LastUpdate":"1980-01-01",
"IsRegistered":true
}
And this is what happens:
The controller receives correct values,
Correct values are added to the context,
And then suddenly all hell breaks loose.
This is the controller code:
[HttpPost]
public async Task<IActionResult> CreateVehicle([FromBody] Vehicle v)
{
context.Vehicles.Add(v);
await context.SaveChangesAsync();
return Ok(v.ModelId);
}
What am I missing here?
I have many to many relationship tables. Sube and User
namespace Odev.Entities
{
public class User
{
[Key]
public int Id { get; set; }
[Required]
[DisplayName("Kimlik No")]
[ StringLength(11)]
[Index(IsUnique = true)]
public string UserName { get; set; }
[ StringLength(8)]
[DisplayName("Şifre")]
public string Password { get; set; }
[DisplayName("Ad Soyad")]
public string NameSurname { get; set; }
[DisplayName("Bölüm")]
public string Bolum { get; set; }
[DisplayName("Dal")]
public string Dal { get; set; }
[DisplayName("Öğrenci No")]
public int OgrenciNo { get; set; }
public int RoleId { get; set; }
public virtual ICollection<Sube> Subes { get; set; }
public virtual List<Notification> Notifications { get; set; }
public virtual List<Homework> Homeworks { get; set; }
public virtual Role Role { get; set; }
}
}
namespace Odev.Entities
{
public class Sube
{
[Key]
public int Id { get; set; }
[DisplayName("Şube")]
public string Sube_Name { get; set; }
public virtual Homework Homework { get; set; }
public virtual ICollection<User> Users { get; set; }
}
}
namespace Odev.DataAccessLayer
{
public class DatabaseContext : DbContext
{
public DatabaseContext() : base("dataConnection")
{
Database.SetInitializer(new OdevInitializer());
}
public DbSet<User> Users { get; set; }
public DbSet<Homework> Homeworks { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Sube> Subes { get; set; }
public DbSet<Notification> Notifications { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
and my ViewModel
namespace Odev.Models{
public class ViewModel{
public string Sube_Name { get; set; }
public string NameSurname { get; set; }
public string UserName { get; set; }
public int UserId { get; set; }
public int SubeId { get; set; }
public User User { get; set; }
public Sube Sube { get; set; }
public Role Role { get; set; }
}}
I want to show User's SubeId:
How I select Sube's id ?
You need connect both entities with a foreign key.
Please, read this doc: Creating a More Complex Data Model for an ASP.NET MVC Application
I'm trying to use Enum support with EF 5 and dot.NET 4.5.
The situation I have is the following.
POCO:
public partial class tbl_pp_Message
{
public tbl_pp_Message()
{
this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public int PriorityId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
[ForeignKey("PriorityId")]
public virtual tbl_pp_MessagePriority tbl_pp_MessagePriority { get; set; }
public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
public partial class tbl_pp_MessagePriority
{
public tbl_pp_MessagePriority()
{
this.tbl_pp_Message = new List<tbl_pp_Message>();
}
public int MessagePriorityId { get; set; }
public string Description { get; set; }
public Nullable<int> DisplayOrder { get; set; }
public bool ShowAlert { get; set; }
public virtual ICollection<tbl_pp_Message> tbl_pp_Message { get; set; }
}
With the code listed above NOT using an ENUM the world is happy.
When I try to add an Enum the POCO will look like this.
[Flags]
public enum MessagePriorityEnum : int
{
NONE = 0,
Urgent = 1,
Normal = 2,
Low = 3
}
public partial class tbl_pp_Message
{
public tbl_pp_Message()
{
this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public MessagePriorityEnum PriorityId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
[ForeignKey("PriorityId")]
public virtual tbl_pp_MessagePriority tbl_pp_MessagePriority { get; set; }
public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
This will not work during a save because it doesn't like the ForeignKey attribute. This error will be thrown during a save.
Schema specified is not valid. Errors:
(129,6) : error 0112: The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'PriorityId' on entity 'tbl_pp_Message' does not match the type of property 'MessagePriorityId' on entity 'tbl_pp_MessagePriority' in the referential constraint 'tbl_pp_MessagePriority_tbl_pp_Message'.
If the navigation for tbl_pp_MessagePriority is removed from tbl_pp_Message POCO. And the navigation removed from tbl_pp_MessagePriority POCO back to tbl_pp_Message then it works.
With out the navigation removed it will generate a SQL statement like this.
insert [dbo].[tbl_pp_Message]
([Subject],
[From],
[Body],
[PriorityId],
[CreateDate],
[CreateById],
[tbl_pp_MessagePriority_MessagePriorityId])
values ('Test ENUM EF Code First 5.0' /* #0 */,
'Daniel.Bivens' /* #1 */,
'Test 01 Enum Body - The Magic Unicorn Edition' /* #2 */,
2 /* #3 */,
'2013-05-23T10:52:09' /* #4 */,
5 /* #5 */,
null)
select [MessageId]
from [dbo].[tbl_pp_Message]
where ##ROWCOUNT > 0
and [MessageId] = scope_identity()
It would be ok if the tbl_pp_MessagePriority_MessagePriorityId was not added to the insert.
What can be done to keep the navigaion in EF code first while using ENUM support? Is there a DataAnnotation or a Mapping API?
Please post any suggestions you may have. This project is not using an EDMX/T4 template.
Working POCO:
public partial class tbl_pp_Message
{
//public tbl_pp_Message()
//{
// this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
//}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public MessagePriorityEnum PriorityId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
//[ForeignKey("PriorityId")]
//public virtual tbl_pp_MessagePriority tbl_pp_MessagePriority { get; set; }
//public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
public partial class tbl_pp_MessagePriority
{
//public tbl_pp_MessagePriority()
//{
// this.tbl_pp_Message = new List<tbl_pp_Message>();
//}
public int MessagePriorityId { get; set; }
public string Description { get; set; }
public Nullable<int> DisplayOrder { get; set; }
public bool ShowAlert { get; set; }
//public virtual ICollection<tbl_pp_Message> tbl_pp_Message { get; set; }
}
The working POCO would be ok if no navigation was needed.
The thing I was missing was setting the look-up table primary key to the same ENUM type instead of an int.
Working POCO with ENUM and navigation.
public partial class tbl_pp_Message
{
public tbl_pp_Message()
{
this.tbl_pp_MessageAction = new List<tbl_pp_MessageAction>();
this.tbl_pp_MessageAttachment = new List<tbl_pp_MessageAttachment>();
this.tbl_pp_MessageDistribution = new List<tbl_pp_MessageDistribution>();
}
public int MessageId { get; set; }
public string Subject { get; set; }
public string From { get; set; }
public string Body { get; set; }
public MessageTypeEnum TypeId { get; set; }
public System.DateTime CreateDate { get; set; }
public int CreateById { get; set; }
[ForeignKey("TypeId")]
public virtual tbl_pp_MessageType tbl_pp_MessageType { get; set; }
public virtual ICollection<tbl_pp_MessageAction> tbl_pp_MessageAction { get; set; }
public virtual ICollection<tbl_pp_MessageAttachment> tbl_pp_MessageAttachment { get; set; }
public virtual ICollection<tbl_pp_MessageDistribution> tbl_pp_MessageDistribution { get; set; }
}
public partial class tbl_pp_MessageType
{
public tbl_pp_MessageType()
{
this.tbl_pp_Message = new List<tbl_pp_Message>();
}
[Key]
public MessageTypeEnum MessageTypeId { get; set; }
public string Description { get; set; }
public Nullable<int> DisplayOrder { get; set; }
public bool ShowAlert { get; set; }
public virtual ICollection<tbl_pp_Message> tbl_pp_Message { get; set; }
}
I use RestSharp in my Windows Phone 7.1 project.
I have a response in XML format here:
https://skydrive.live.com/redir.aspx?cid=0b39f4fbbb0489dd&resid=B39F4FBBB0489DD!139&parid=B39F4FBBB0489DD!103&authkey=!AOdT-FiS6Mw8v5Y
I tried to deserialize that response to a class:
public class fullWall
{
public _user user { get; set; }
public int numberOfFriend { get; set; }
public int numberOfPhoto { get; set; }
public List<timhotPhotos> timhotPhotos { get; set; }
public fullWall()
{
timhotPhotos = new List<timhotPhotos>();
}
}
All properties are ok except the timhotPhotos list, as you can see here:
timhotPhotos class:
public class timhotPhotos
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public double width { get; set; }
public double height { get; set; }
public DateTime createdDate { get; set; }
public _user user { get; set; }
public int numOfComment { get; set; }
public int numOfRate { get; set; }
public int numOfView { get; set; }
public bool rated { get; set; }
}
Where am I wrong?
You'll have to change the default XML deserializer to the DotNetXmlDeserializer, like this:
RestClient client;
client.AddHandler("application/xml", new DotNetXmlDeserializer());
Then, add the XmlElement attribute to the List<timhotPhotos> timhotPhotos property like this:
public class fullWall
{
public _user user { get; set; }
public int numberOfFriend { get; set; }
public int numberOfPhoto { get; set; }
[System.Xml.Serialization.XmlElement()]
public List<timhotPhotos> timhotPhotos { get; set; }
public fullWall()
{
timhotPhotos = new List<timhotPhotos>();
}
}
Now it should work fine!