MVC Remote validation - transfer of entered data - c#

How to pass form data to remote mvc validation? Here is my model:
[Remote(action: "VerifyContinousOfReservation", controller: "Reservation",
AdditionalFields = nameof(EndOfReservation))]
public DateTime StartOfReservation { get; set; } = DateTime.Now;
[Remote(action: "VerifyContinousOfReservation", controller: "Reservation",
AdditionalFields = nameof(StartOfReservation))]
public DateTime EndOfReservation { get; set;} = DateTime.Now;
Here is my controller:
[AcceptVerbs("GET", "POST")]
public IActionResult VerifyContinousOfReservation(string StartOfReservation, string EndOfReservation)
{
var start = StartOfReservation;
var end = EndOfReservation;
return Json(true);
}
I want to know what user send from input and check that there is no reservation in this data range. But start and end is null.
I don't know if I'm taking the right approach.
I have a JSON file with reserved dates. I want to use validation to check if the date range specified by the user does not contain a reserved date.

Related

get cultureinfo of the actual system in MVC 3

I'm doing a Web .Net application, on MVC. I create a controller:
[HttpPost]
public JsonResult Fechas() {
DateTime fecha = DateTime.Now;
List<listas.Ffechas> actualFecha = new List<listas.Ffechas>();
actualFecha.Add(new listas.Ffechas( fecha.Year.ToString(),
fecha.Month.ToString(),
fecha.Hour.ToString(),
fecha.Minute.ToString(),
fecha.Second.ToString(),
fecha.Millisecond.ToString()
));
return Json(new { actualFecha, JsonRequestBehavior.DenyGet });
}
This controller its based on a List Model:
public class Ffechas {
public string FYear { get; set; }
public string FMonth { get; set; }
public string FHour { get; set; }
public string FMinute { get; set; }
public string FSecond {get;set;}
public string FMiliseconds {get;set;}
public Ffechas(string CYear,string CMonth, string CHour, string CMinute, string CSecond, string CMiliseconds) {
FYear = CYear;
FMonth = CMonth;
FHour = CHour;
FMinute = CMinute;
FSecond = CSecond;
FMiliseconds = CMiliseconds;
}
}
And send the information in Json format.
The point here is, How I can detect the actual culture or region language of the system and apply to my fecha Datetime, example:
if the actual system culture is ("en-us") the date is sended on that format or if the actual system culture is ("es-mx") the date is sended on that form.
I dont have problems with list or something like that, my issue is detect the culture system status and with this I can send through json the correct format. thanks for your help.

asp.net MVC 4 simple sorting

I am using ASP.net MVC4 and am trying to accomplish a simple sort , so far I have found how to make the whole database sortable - by using ActionLink buttons in my View (failed to make it work btw...), but what I am trying to accomplish is a permanently sorted database.
My view and controller are both scaffolded at the moment, no changes made to this part. I am trying to make the record with the least TimeRemaining to always show up on top of the list.
Thanks!
My Database:
public class EquipmentDataBase {
public int ID { get; set; }
[DisplayName("Name")]
public string equipment { get; set; }
[DisplayName("Inv.Nr.")]
public string InventoryNumber { get; set; }
[DisplayName("Location")]
public string Location { get; set; }
[Required(ErrorMessage ="Please specify date")]
[DataType(DataType.Date)]
[DisplayName("Next Inspection")]
public DateTime NextInspectionDate { get; set; }
[Required(ErrorMessage ="PleaseSpecifyRegistrationDate")]
[DataType(DataType.Date)]
public DateTime RegistrationDate { get; set; }
public string Responsible { get; set; }
public TimeSpan TimeRemaining
{
get
{
return (NextInspectionDate - DateTime.Today);
}
}
My Controller:
namespace PeriodicInspections.Controllers {
public class EquipmentDBController : Controller
{
private EquipmentDbContext db = new EquipmentDbContext();
// GET: EquipmentDB
public ActionResult Index()
{
return View(db.equipment.ToList());
}
If you want to have it sorted by the same criteria, the best approach is to sort them at database level. You can achieve this by changing the code in the controller as follows:
// GET: EquipmentDB
public ActionResult Index()
{
return View(db.equipment.OrderBy(x => x.NextInspectionDate).ToList());
}
The OrderBy sorts the data by NextInspectionDate. This property is present at database level in contrast to the helper property TimeRemaining that is only available in the .NET code. As regards the sort order, this will make no difference.
Use Linq. instead of
return View(db.equipment.ToList());
use
return View(db.equipment.ToList().OrderBy(e=>e.TimeRemaining );

MVC data annotation on client side conditional

i have a form wherein there is conditional textboxes.i have used mvc dataannotation client side on dropdown change i hide two textboxes data validation error is not fired but in controller i get model error in if (ModelState.IsValid).How can i do condtional handling of data annotation in client side only.I dont want to use fullproof validation or other third party.
i tried removing the data-val-* attributes using jquery still getting error in controller.refer image if i select asset type laptop then sim plan and price is hidden dataannotation dont fire which is correct but get error on controller.
Model:
[Required(ErrorMessage = "Please Enter Make")]
public string Make { get; set; }
[Required(ErrorMessage = "Please Enter Model")]
public string Model { get; set; }
[Required(ErrorMessage = "Please Enter Sim Plan")]
public string SimPlan { get; set; }
[Required(ErrorMessage = "Please Enter Price")]
public decimal? Price { get; set; }
there's a much better way to add conditional validation rules in MVC3. Have your model inherit IValidatableObject and implement the Validate method:
public class Person : IValidatableObject
{
public string Name { get; set; }
public bool IsSenior { get; set; }
public Senior Senior { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (IsSenior && string.IsNullOrEmpty(Senior.Description))
yield return new ValidationResult("Description must be supplied.");
}
}
see more of a description at http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
If you trying to manually clear validation error which u have not used in your view than i would suggest you clear them before checking modelstate.
Ex:
[HttpPost]
public ActionResult Register(Model objModel )
{
foreach (string Key in ModelState.Keys)
{
if ((Key.Equals("Email")) || (Key.Equals("Password")))
{
ModelState[Key].Errors.Clear();
}
}
if (ModelState.IsValid)
{
//Do the work
}
}
In the above example i have passed the values in Model and i didn't pass any value for Email and password, so in controller i am clearing those Key which is present in ModelState.

Validation using Regular Expression

Im having some problems utilizing RegularExpression attribute in a ASP.net MVC project.
It seems to work client side, it goes away when it fits, however then upon post action, the model state is checked for being valid, it ends up posting error, that it must follow the regular expression.
I have tried theese following:
^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}$
^\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}$
Essentially it must catch 14/12/2014 14:20 as input.
Any ideas? I'm lost.
Model:
[Required]
[Display(Name = "TimeDisplay", ResourceType = typeof(Resources.Models.Log))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
[RegularExpression(#"^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}$")]
public DateTime Time { get; set; }
Controller Action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Log log)
{
if (ModelState.IsValid)
{
db.Logs.Add(log);
db.SaveChanges();
TempData["Notification"] = AlertGenerator.GenerateAlert(AlertGenerator.Level.Success, "Success! Log Saved");
return RedirectToAction("Index");
}
return View(log);
}
As I know, MVC will use current CultureInfo (on server) to parse DateTime format, so you cannot directly binding "dd/MM/yyyy HH:mm" to your entity.
My solution is creating ViewModel then use DateTime.ParseExact(...) to parse the date:
Model:
[Display(Name = "TimeDisplay", ResourceType = typeof(Resources.Models.Log))]
[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
public DateTime Time { get; set; }
ViewModel
[Display(Name = "TimeDisplay", ResourceType = typeof(Resources.Models.Log))]
[Required]
public string Time { get; set; }
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(LogViewModel logViewModel)
{
if (ModelState.IsValid)
{
// convert from ViewModel to Entity Model
Log log = new Log(logViewModel);
// parse the time
log.Time = DateTime.ParseExact(logViewModel.Time, "dd/MM/yyyy HH:mm", null);
db.Logs.Add(log);
db.SaveChanges();
TempData["Notification"] = AlertGenerator.GenerateAlert(AlertGenerator.Level.Success, "Success! Log Saved");
return RedirectToAction("Index");
}
return View(log);
}

ASP.NET MC3 - single interface to create a record and the supporting records

I have the beginnings of an ASP.NET MVC3 application that is supposed to implement scheduling. I have the following in my model:
public class Schedule
{
public int ScheduleID { get; set; }
public bool isDisabled { get; set; }
[DisplayName("For Delivery")]
public bool isDeliver { get; set; }
public int Count { get; set; }
public virtual ICollection<TimeofDay> Times { get; set; }
public virtual Location Location { get; set; }
public int Week { get; set; }
public int weekday { get; set; }
}
public class TimeofDay
{
[Key]
public int TimeID {get;set;}
public DateTime Time { get; set; }
}
The model is supposed to accept 0 or more Time of Day entities that I pass by using JavaScript to create a new input field:
function createtimefield() {
var TimeDiv = document.getElementById('timefields');
var newDivInput = document.createElement("input");
newDivInput.name = "Times";
idText="Time" + GLOBAL_timeDivIdCount++;
newDivInput.id = idText;
newDivInput.value = "12:00 am";
TimeDiv.appendChild(newDivInput);
}
My Controller will work file for accepting the data passed up until I add data to the time fields. This is supposed to create new entities in the TimeofDay table that gets generated by the model, and link back to the the ScheduleID. I don't want two interfaces to input this simple data, but can't seem to find the way to create both entities with MVC3 in a single action. Anyone have any ideas?
Andrew
(Thank you for reading)
As requested the controller was:
public ActionResult Create(Schedule schedule, string[] schedTimes)
{
if (ModelState.IsValid)
{
Schedule newschedule = db.Schedule.Add(schedule);
db.SaveChanges();
return RedirectToAction("Index");
}
......
}
I now realize I need to create a view model that will encompass both my schedule class and an array of strings. I will create the schedule and then iterate through the array of strings and create TimeofDay objects
for inputs to bind with times collection ur form fields need to have indexed names like
Times[0].TimeID // this would probably be hidden field
Times[0].Time
Times[1].TimeID
Times[1].Time
.
.
Times[n].TimeID
Times[n].Time
when you do this there might be other issues when deleting rows from the middle. there are lot of blog posts on this out there. Phil haack's post is my favorite as it explains in very simple way how can you have non sequential indices for list binding. For more links please look at my answer to this question
I attempted to create a view model to support this by extending my model as follows:
public class ScheduleCreate
{
public Schedule schedule {get;set;}
public string[] schedTimes {get;set}
}
I then modified my view by changing:
#model scheduler.Models.Schedule
to:
#model scheduler.Models.ScheduleCreate
I additionally changed all of the model.(parameter) to model.schedule.(parameter)
Then I changed my controller to:
public ActionResult Create(ScheduleCreate mod)
{
if (ModelState.IsValid)
{
Schedule newschedule = db.Schedule.Add(mod.schedule);
if (mod.schedTime != null)
{
foreach (string instanceTime in mod.schedTimes)
{
newschedule.Times.Add(new {Time = DateTime.Parse(instanceTime) }); // unteseted
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
PopulateDropDown();
return View(mod.schedule);
}

Categories

Resources