MVC best practice for date change possible redirect
I am looking to see anyone could inform me of MVC best practice for the following functionality.
A user is able to create a form, specifying a date and other details for submission. Whilst completing the form, if the user changes the date field I want the application to check whether a form for that date already exists, before (through a message box) asking the user if they wish to load it. If form doesn't exist, I just n开发者_Go百科eed the date change to be excepted.
Should this be some sort of Ajax request?
In an ideal world, you would support the following 2 scenarios:
1) A server side check/validation step that, upon submission of the form and discovery of another form of the same date, would redirect the user back to the original submission page (without any data loss) notifying them of the possible duplicate, and give them the option to load the form from there.
2) A client side AJAX request that submits the date to the server asking the basic question "do we already have a form with this date", and, if yes, giving them the option to load the from there. This option is nice because it let's the user know (perhaps before they finished all the manual labor of filling out the form) that there is another already entered. You user would be thankful for saving their time, and you save a round trip to the server.
You cannot rely no the JavaScript asynchronous request to enforce your business rules for you, as this can be easily circumvented, both deliberately or unknowingly (by users with JavaScript disabled)
Use jQuery's Remote Validation with MVC 3. This will return an error message from your controller method (if you don't return true or false but a string instead. This is a generic demo but it should give you an idea. You will still need to validate on the server as well as Matt said but I wanted to provide this as additional 'how to' details on item #1 above.
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Please enter a valid e-mail address")] [Required()] [Display(Name = "Email Address")] [Remote("EmailAddressUsed", "Demo", ErrorMessage = "Email Address Already On File")] public string EmailAddress { get; set; }
in your controller
public JsonResult EmailAddressUsed(string emailAddress) { if (emailAddress == "test@no.com") { return Json(emailAddress + " is already in use.", JsonRequestBehavior.AllowGet); } else { return Json(true, JsonRequestBehavior.AllowGet); } }
精彩评论