I have a model where i have scaffold it with Mvc Scaffolding, All Fields with DateTime Property in my model are marked as Required i mean i can not enter a null value in it. Even though in my model there is no [Required] attribute for Date fields. I want to get rid of this issue, any idea?
Here is my Model.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCMembershipBootstrap.Models.FirstComponent
{
public class FirstCmActivity
{
public int FirstCmActivityId { get; set; }
public string Name { get; set; }
public DateTime PlannedStartDate { get; set; }
public DateTime PlannedEndDate { get; set; }
public DateTime OngoingStartDate { get; set; }
public DateTime OngoingEndDate { get; set; }
public DateTime FinishedDate { get; set; }
public string GizResponsible { get; set; }
public string PartnerResponsible { get; set; }
public string swAfghanSide { get; set; }
public string swGiz { get; set; }
public string swRodeco { get; set; }
public string swExtern { get; set; }
public string EquipmentNeeds { get; set; }
public string EquipmentExist { get; set; }
public string MileStone { get; set; }
public int FirstCmOutputId { get; set; }
public virtual FirstCmOutput Output { get; set; }
}
}
Here is My Controller...
public class FirstCmActivitiesController : Controller
{
private OPandMEContext context = new OPandMEContext();
//
// GET: /FirstCmActivities/
public ViewResult Index()
{
return View(context.FirstCmActivities.ToList());
}
public ViewResult Report()
{
return View();
}
//
// GET: /FirstCmActivities/Details/5
public ViewResult Details(int id)
{
FirstCmActivity firstcmactivity = context.FirstCmActivities.Single(x => x.FirstCmActivityId == id);
return View(firstcmactivity);
}
//
// GET: /FirstCmActivities/Create
public ActionResult Create()
{
ViewBag.PossibleFirstCmOutputs = context.FirstCmOutputs;
return View();
}
//
// POST: /FirstCmActivities/Create
[HttpPost]
public ActionResult Create(FirstCmActivity firstcmactivity)
{
if (ModelState.IsValid)
{
context.FirstCmActivities.Add(firstcmactivity);
context.SaveChanges();
Response.Redirect("http://localhost:53785/firstcmActivities/Create#services");
}
ViewBag.PossibleFirstCmOutputs = context.FirstCmOutputs;
return View(firstcmactivity);
}
Thanks
Just Correct your properties of Datetime as nullable.
Example :-
public DateTime? PlannedStartDate { get; set; }
Related
I have a model in another model. When I try to check the modelstate it is invalid. This is because the other model in this model is null.
Project.cs:
using System.ComponentModel.DataAnnotations;
namespace Toolbox.Models
{
public class Project
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public WorkPreparation WorkPreparation { get; set; }
}
}
WorkPreparation.cs:
using System.ComponentModel.DataAnnotations;
namespace Toolbox.Models
{
public class WorkPreparation
{
[Key]
public int Id { get; set; }
public int ProjectId { get; set; }
public CentralHeating CentralHeating { get; set; }
public Pluming Pluming { get; set; }
public Ventilation Ventilation { get; set; }
public Project Project { get; set; }
}
}
Does anybody have any suggestion?
If you use .net6, try to remove <Nullable>enable</Nullable> in your project.csproj.
I want to use mapbox matching in ASP.NET Core. This link you can get response https://api.mapbox.com/matching/v5/mapbox/driving/..
I want to convert this response to dynamic json in Asp.net core, I use this line
var jsonResponse = JsonConvert.DeserializeObject(mapResponse);
but I get empty values. Any help?
Firstly, The API you have shared I got follwing response using
postman:
If its same what you are getting then I follow below steps to retrive
the value from the API response in C# asp.net core controller
Model You should have :
public class Admin
{
public string iso_3166_1_alpha3 { get; set; }
public string iso_3166_1 { get; set; }
}
public class Leg
{
public List<object> via_waypoints { get; set; }
public List<Admin> admins { get; set; }
public double weight { get; set; }
public double duration { get; set; }
public List<object> steps { get; set; }
public double distance { get; set; }
public string summary { get; set; }
}
public class Matching
{
public double confidence { get; set; }
public string weight_name { get; set; }
public double weight { get; set; }
public double duration { get; set; }
public double distance { get; set; }
public List<Leg> legs { get; set; }
public string geometry { get; set; }
}
public class Tracepoint
{
public int matchings_index { get; set; }
public int waypoint_index { get; set; }
public int alternatives_count { get; set; }
public double distance { get; set; }
public string name { get; set; }
public List<double> location { get; set; }
}
public class MapResponseClass
{
public List<Matching> matchings { get; set; }
public List<Tracepoint> tracepoints { get; set; }
public string code { get; set; }
public string uuid { get; set; }
}
Asp.net core Controller:
public async Task<IActionResult> CallMapAPI()
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.mapbox.com/matching/v5/mapbox/driving/-117.17282,32.71204;-117.17288,32.71225;-117.17293,32.71244;-117.17292,32.71256;-117.17298,32.712603;-117.17314,32.71259;-117.17334,32.71254?access_token=pk.eyJ1Ijoibm92ZXJzbWFwIiwiYSI6ImNreTdwc3ppNTE3dzkyb3B2MnVzNXpueTUifQ.csYTL2GKkl99Yqk_TQjr5w");
response.EnsureSuccessStatusCode();
string mapAPIjson = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<MapResponseClass>(mapAPIjson);
}
catch (Exception ex)
{
throw;
}
return data;
}}
Output:
Note:
You should bound your class as per your API response. What I am
assuming of your empty values is you haven't converted the relevant
class accordingly. I hope above steps guided you accordingly.
I'm trying to make a nested collection search and I'm really struggling.
My expected result is: I would like to make a search and find all the powerUp objects by a certain date. (PowerUpDate property - that's the searching criteria)
User Model:
public class AppUser : IdentityUser
{
public ICollection<Hero> Heroes { get; set; }
}
Hero Model:
[Table("Heroes")]
public class Hero
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Ability { get; set; }
[Required]
public string SuitColors { get; set; }
public double CurrentPower { get; set; }
public double StartingPower { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public ICollection<PowerUp> PowerUps { get; set; }
public AppUser AppUser { get; set; }
[Required]
public string AppUserId { get; set; }
}
PowerUp Model:
[Table("PowerUps")]
public class PowerUp
{
public int Id { get; set; }
[Required]
public double PowerUpIncrement { get; set; }
[Required]
public DateTime PowerUpDate { get; set; } = DateTime.Now;
public Hero Hero { get; set; }
[Required]
public int HeroId { get; set; }
}
DataContext:
public class DataContext : IdentityDbContext<AppUser>
{
public DataContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Hero>().HasMany(hero => hero.PowerUps).WithOne(powerUp => powerUp.Hero)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<AppUser>().HasMany(user => user.Heroes).WithOne(hero => hero.AppUser)
.OnDelete(DeleteBehavior.Cascade);
}
}
Could someone please explain to me how can I implement such a search on a nested collection?
Inject your AppUser user using Dependency injection
(better use the repository pattern) anyway it should be something like this: user.Heroes.PowerUps.OrderBy(x=>x.PowerUpDate == Datetime.Now).ToList();
x.PowerUpDate == To whatever date you will insert
I m trying this tutorial: Requesting a Derived Entity Collection
When i make this request:
GET : http://tdd.stooges.com.my/api/paymentAbles?$format=application/json
I get this response:
{
"#odata.context":"http://tdd.stooges.com.my/api/$metadata#paymentAbles",
"value":[
{
"#odata.type":"#EFDB.Topup","id":1
},
{
"#odata.type":"#EFDB.Order","id":7
}
]
}
It is OK. But when i try this request:
GET : http://tdd.stooges.com.my/api/paymentAbles/EFDB.Order?$format=application/json
I get the response 404
I found a similar question on stackoverflow:
WCF Data Service gives 404 when making OData requests for derived types,
but the solution make all http request return 500 internal error.
How can I solve the problem? You can use this site: http://tdd.stooges.com.my for testing (for example using firebug to view teh request/response details).
Update :
modelBuilder.Entity<PaymentAble>()
.Map<Topup>(s => s.Requires("type").HasValue("topup"))
.Map<Order>(m => m.Requires("type").HasValue("order"));
[Table("payment_able")]
public abstract class PaymentAble
{
[Key]
public int id { get; set; }
public double amount { get; set; }
public string code { get; set; }
public string statusEnum { get; set; }
[ForeignKey("member")]
public int member_id { get; set; }
public virtual Member member { get; set; }
public virtual Payment payment { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTimeOffset rowCreatedDT { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[ConcurrencyCheck]
public byte[] rowVersion { get; set; }
[ForeignKey("rowCreator")]
public int rowCreatorLoginPerson_id { get; set; }
[ForeignKey("rowLastModifiedBy")]
public int rowLastModifiedByLoginPerson_id { get; set; }
public virtual LoginPerson rowCreator { get; set; }
public virtual LoginPerson rowLastModifiedBy { get; set; }
}
public class Topup : PaymentAble
{
}
public class Order : PaymentAble
{
[Column("order_GSTPercent")]
public double GSTPercent { get; set; }
[Column("order_clientName")]
public string clientName { get; set; }
[Column("order_clientEmail")]
public string clientEmail { get; set; }
[Column("order_clientHp")]
public string clientHp { get; set; }
public virtual List<OrderItem> items { get; set; }
}
[Table("order_item")]
public class OrderItem : RowInfo
{
[Key]
public int id { get; set; }
public int qty { get; set; }
public double amount { get; set; }
[ForeignKey("order")]
public int order_id { get; set; }
public virtual Order order { get; set; }
public virtual OrderCard card { get; set; }
}
public static IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<LoginPerson>("loginPersons");
builder.EntitySet<Admin>("admins");
builder.EntitySet<Member>("members");
builder.EntitySet<Card>("cards");
builder.EntitySet<CardPackage>("cardPackages");
builder.EntitySet<Game>("games");
builder.EntitySet<Img>("imgs");
builder.EntitySet<Currency>("currencys");
builder.EntitySet<Topup>("topups");
builder.EntitySet<Order>("orders");
builder.EntitySet<OrderItem>("OrderItems");
builder.EntitySet<Payment>("payments");
builder.EntitySet<PaymentAble>("paymentAbles");
builder.Namespace = "RPC"; //test only
var gettotalFn = builder.EntityType<PaymentAble>().Collection.Function("getTotal");
gettotalFn.Returns<int>();
return builder.GetEdmModel();
}
config.MapODataServiceRoute("odata", "api", GetModel());
[ODataRoutePrefix("paymentAbles")]
public class PaymentAblesController : BaseController
{
[ODataRoute("")]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<PaymentAble> get()
{
return db.paymentAbles;
}
public async Task<IHttpActionResult> getTotal()
{
return Ok(15);
}
}
I would like to know how do I define the viewmodel from below class.
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool HasCompleted { get; set; }
public DateTime DeadLine { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? LastModified { get; set; }
}
From above model, only Id, Name, HasCompleted and Deadline fields would displayed to the user. Otherwise fields CreatedDate and LastModified fields would be handled internally.
Initially the database table will be created with all the aforementioned fields. But, as mentioned, in order to avoid over posting attacks, I have created a view model with all the required fields. Now, the structure looked as below.
public class TestModel
{
public TestVM testVM { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? LastModified { get; set; }
}
public class TestVM
{
public int Id { get; set; }
public string Name { get; set; }
public bool HasCompleted { get; set; }
public DateTime DeadLine { get; set; }
}
If would still like to maintain a single database table and make CRUD operations. But, I have a roadblock here in below action.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(TestVM item)
{
//Once the values are bound to TestVM. How do I get the instance of the TestModel to update the LastModified property here??
}
Could someone please advise ?
Regards,
Ram
Remove TestViewModel from TestModel class.
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool HasCompleted { get; set; }
public DateTime DeadLine { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? LastModified { get; set; }
}
public class TestViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool HasCompleted { get; set; }
public DateTime DeadLine { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(TestViewModel item)
{
var testModel = new TestModel
{
Name = item.Name,
HasCompleted = item.HasCompleted,
DeadLine = item.DeadLine
};
//testModel.CreateDate = DateTime.Now;
}
You can also use Bind Attribute for prevent Binding CreatedDate and LastModified fields:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Exclude("CreatedDate", "LastModified"))]TestModel item)
{
}