Disable day in date picker - asp.net-mvc

I am trying to make an appointment page in MVC4. It is working well but I would like to disable the date which is chosen. Here is my controller to make an appointment:
public ActionResult Make()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Make(Models.AppModel User)
{
if (Session["UserEmail"] != null)
{
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var app = new Appointment();
app.Date = (DateTime)User.Date;
app.Description = User.Description;
app.Status = "isPending";
app.PatientNo = patient.PatientNo;
app.AppNo = Guid.NewGuid().GetHashCode();
db.Appointments.InsertOnSubmit(app);
db.SubmitChanges();
}
}
else
{
return RedirectToAction("Index", "User");
}
return RedirectToAction("Index", "Patient");
}
//
}
}
and here is my view with the datepicker
#model DentAppSys.Models.AppModel
#{
ViewBag.Title = "Appointment";
}
<link type="text/css" rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
#Html.ValidationSummary(true, "");
<div>
<fieldset>
<legend>Get an Appointment</legend>
<div>#Html.LabelFor(u => u.Date)</div>
<div>
#Html.TextBoxFor(u => u.Date, htmlAttributes: new { id = "DatePicker" })
#Html.ValidationMessageFor(u => u.Date)
</div>
<div>#Html.LabelFor(u => u.Description)</div>
<div>
#Html.TextBoxFor(u => u.Description)
</div>
<input type="submit" value="Submit" class="footer_btn" />
</fieldset>
</div>
}
<script type="text/javascript">
$(function () {
$("#DatePicker").datepicker();
});
</script>

How about trying:
#Html.TextBoxFor(u => u.Date, htmlAttributes: new { id = "DatePicker", readonly = "readonly" })

Related

Validation of the form submitted by Ajaxform jQuery plugin in ASP.NET MVC 5

public class File
{
[Key]
public int FileID { get; set; }
[Display(Name = "atachfile")]
[MaxLength(150)]
public string atachFile{ get; set; }
}
I wrote the controller codes of the editing section like this...
// GET: /Users/FileUpload/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
File file = db.Files.Find(id);
if (file == null)
{
return HttpNotFound();
}
return View(file);
}
// POST: /Users/FileUpload/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "FileID,atachFile")] File file, HttpPostedFileBase LearnAtach , int id)
{
if (ModelState.IsValid)
{
if (LearnAtach != null)
{
if (file.atachFile != null)
{
System.IO.File.Delete(Server.MapPath("/File/LearnAtach/" + file.atachFile));
}
string[] FileExtension = { ".zip" };
string FileType = Path.GetExtension(LearnAtach.FileName);
double FileSize = (LearnAtach.ContentLength / 1024.0) / 1024;
if (FileExtension.Contains(FileType.ToLower()))
{
if (FileSize > 950)
{/
ViewBag.sizeatach = "error..filexize>950";
return View(file);
}
file.atachFile = Guid.NewGuid() + Path.GetExtension(LearnAtach.FileName);
LearnAtach.SaveAs(Server.MapPath("/File/LearnAtach/" + file.atachFile));
}
else
{
ViewBag.typeatach = "filyType != zip";
this.TempData["UnSuccessMessage"] = "filyType != zip";
return View(file);
}
}
fileRepository.UpdateFile(file);
fileRepository.save();
return RedirectToAction("Index");
}
return View(file);
}
View markup:
#model DataLayer.File
#using (Html.BeginForm("Edit", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data", id = "fileform" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.FileID)
<div class="form-group">
#Html.LabelFor(model => model.atachFile, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.atachFile, new { type = "file", Name = "LearnAtach" })
#Html.ValidationMessageFor(model => model.atachFile)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="submit" class="btn btn-success" />
</div>
</div>
</div>
}
<div class="progress progress-striped" style="direction: ltr">
<div class="progress-bar progress-bar-success">0%</div>
</div>
<br /><br />
#section scripts
{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/modal.js"></script>
<script>
$(document).ready(function() {
var bar = $('.progress-bar');
var percent = $('.progress-bar');
var status = $('#status');
$("#fileform").ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
//show preloder
},
success: function() {
var percentVal = '100%';
bar.width(percentVal);
percent.html(percentVal);
//hide preloder
$("#Success").modal();
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
</script>
}
Now the file is uploaded but the validators are not applied .. How can I show the filesize limit and filetype the file on the client side to the user and apply
In fact, if the condition of file size and format is also wrong, the uploaded file will be saved in the (/File/LearnAtach)folder, but because the condition is incorrect, its path will not be stored in the database.
Also, if the condition is true, the condition whether this file already exists or deletes the previous one will not be checked. Thanks

JQuery Datetimepicker date selected does not match date today

I am working on a scheduling project in MVC 5. I want to check the Date Selected against current Date. If they match, display the scheduled appointment for Today' date only in a view. Currently, the appointments do not display when I add "appointment.AppointmentDate == DateTime.Now". Instead the View duplicates "No Appointments Today'.
I have researched through StackOverFlow and other sites to try and figure out with no luck. One attempt was adding ".data('date') in the Create view: " $('#datetimepicker1.data('date'), #datetimepicker2').datetimepicker " to set the type as Date but was unsuccessful. I am a beginner and hope someone may be able to help me in the right direction. Thanks.
My code is below:
MODEL:
public enum AppointmentTime
{
_1pm_to_2pm, ApplicationDbContext _dbContext = new ApplicationDbContext();
public ActionResult Create(int id)
{
Property property = _dbContext.Properties.SingleOrDefault(b => b.PropertyID == id);
ViewBag.propertyName = property.PropertyName;
Consultation consultation = new Consultation();
consultation.PropertyID = id;
return View(consultation);
}
[HttpPost]
public ActionResult Create(Consultation consultation)
{
try
{
if (ModelState.IsValid)
{
Property property = _dbContext.Properties.SingleOrDefault(b => b.PropertyID == consultation.PropertyID);
property.Consultations.Add(consultation);
_dbContext.SaveChanges();
return RedirectToAction("Details", "Property", new { id = property.PropertyID });
}
return View();
}
catch
{
return View("Error");
}
}
_2pm_to_3pm,
_3pm_to_4pm,
_4pm_to_5pm,
_5pm_to_6pm
}
public class Consultation
{
[Key]
public int AppointmentID { get; set; }
[ForeignKey("Property")]
public int PropertyID { get; set; }
[Display(Name = "Enter your name")]
public string AppointmentName { get; set; }
[Required]
[Display(Name = "Email")]
public string AppointmentEmail { get; set; }
[Display(Name = "Select Date")]
[UIHint("AppointmentDate")]
[Required]
public DateTime AppointmentDate { get; set; }
public AppointmentTime AppointmentTime { get; set; }
public virtual Property Property { get; set; }
}
CONTROLLOR:
[Authorize(Roles = "Admin")]
public ActionResult AdminAppointmentView(Consultation consultaion)
{
var appointments = _dbContext.Consultations.ToList();
return View(appointments);
}
CREATE VIEW
#model OpenProperties.Models.Consultation
#{
ViewBag.Title = "Create Appointment";
}
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css"
rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen"
href="http://tarruda.github.com/bootstrap-datetimepicker/assets/css/bootstrap-datetimepicker.min.css">
#using (Html.BeginForm(new { enctype = "multipart/form-data", id = "form1" }))
{
#Html.ValidationSummary(true)
<div>
#Html.HiddenFor(model => model.PropertyID)
<br />
<div class="form-group">
#Html.LabelFor(m => m.AppointmentName)
#Html.TextBoxFor(m => m.AppointmentName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.AppointmentEmail)
#Html.TextBoxFor(m => m.AppointmentEmail, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.AppointmentTime, new { #class = "control-label col-md-2" })
#Html.EnumDropDownListFor(model => model.AppointmentTime)
#Html.ValidationMessageFor(model => model.AppointmentTime)
</div>
<div id="datetimepicker1" class="input-append date">
#Html.TextBoxFor(m => m.AppointmentDate, "{0:dd/MM/yyyy HH}",
new { placeholder = "App Date", #class = "dtPicket" })
<span class="add-on">
<i data-time-icon="icon-time"
data-date-icon="icon-calendar"></i>
</span>
</div>
<br />
<br />
<input type="submit" value="Submit" />
</div>
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.pt-BR.js">
</script>
<script type="text/javascript">
$('#datetimepicker1, #datetimepicker2').datetimepicker({
format: 'dd/MM/yyyy'
});
</script>
}
AdminAppointmentView VIEW:
#model IEnumerable<OpenProperties.Models.Consultation>
<h2>Todays Appointments</h2>
#foreach (var appointment in Model)
{
if (appointment.AppointmentDate == DateTime.Now)
{
<li>
<ul>#appointment.AppointmentID</ul>
<ul>#appointment.AppointmentDate</ul>
<ul>#appointment.AppointmentEmail</ul>
<ul>#appointment.AppointmentName</ul>
<ul>For Property ID: #appointment.PropertyID</ul>
</li>
}
else
{
<ul> No Appointments Today </ul>
}
}
Just at first Glance.
if (appointment.AppointmentDate == DateTime.Now)
(
}
Is the date Format is same for appointment.AppointmentDate and DateTime.Now??.
If not just add Tostring Method to these date.
ex.
DateTime.Now.ToString("MMMM dd, yyyy")
2) You might check the // Difference in days, hours, and minutes. between the date as well. Instead of comparing
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
3) You can format date in datetime Picker as follows.
$('#datepicker').datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "hh:mm:ss"
});
4) Also could you please put Script and datepicker code before the html
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.pt-BR.js">
</script>
<script type="text/javascript">
$('#datetimepicker1, #datetimepicker2').datetimepicker({
format: 'dd/MM/yyyy'
});
</script>

"Controller, Action, Model" not all code paths return a value

I am really confused by this error "not all code paths return a value" on my action PostResponse. I have stared at my model, controller and view for hours and I think I have all paths covered. Of course the project won't build, so I can't debug further.
My action
// POST: /Questions/ViewQuestion/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostResponse([Bind(Include = "UserId,QuestionID,Answer,Source,Status,DateStamp")] Response response)
{
if (ModelState.IsValid)
{
db.Responses.Add(response);
db.SaveChanges();
}
}
My view
#model Template.Models.Question
#using Microsoft.AspNet.Identity
#{
ViewBag.Title = "View question";
var qtype = Model.QuestionTypeId;
ViewBag.Number = Model.Id - 7;
}
#using (Html.BeginForm("Question", "ViewQuestion", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
<div>
<h4>Question ##ViewBag.Number</h4>
<hr />
<h1> #Model.Question1</h1>
</div>
<div class="form-group">
#switch (qtype)
{
case 1:
// Textbox
#Html.TextArea("Answer", new { #class = "form-control", rows = "4", col = "5" });
break;
case 2:
// Dropdown
<select class="form-control" id="Answer">
#foreach (var item in Model.QuestionOptions.OrderBy(o => o.QuestionOptionRanking))
{
<option value="#item.QuestionOption1">#item.QuestionOption1</option>
}
</select>
break;
case 3:
// Checkbox
<div class="checkbox">
#foreach (var item in Model.QuestionOptions.OrderBy(o => o.QuestionOptionRanking))
{
<input type="checkbox" name="Answer" value="#item.QuestionOption1" /> #item.QuestionOption1 <br />
}
</div>
break;
case 4:
// Radio buttons
foreach (var item in Model.QuestionOptions.OrderBy(o => o.QuestionOptionRanking))
{
<div class="radio">
<label>
<input type="radio" name="Answer" value="#item.QuestionOption1" />
#item.QuestionOption1
</label>
</div>
}
break;
}
</div>
#using Template.Models.Response
#Html.HiddenFor(r => r.Responses, new { UserId = User.Identity.GetUserId(), Source = "Web", Status = "New", DateStamp = System.DateTime.Now })
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Answer" />
</div>
</div>
<br />
<hr />
<p>
#Html.ActionLink("Previous", "ViewQuestion", new { id = Model.Id - 1 }) |
#Html.ActionLink("Next", "ViewQuestion", new { id = Model.Id + 1 })
</p>
The page displays perfectly, but I can't test the post action as I cannot build with the current error.
Worked it out; but it was almost from scratch, as I created a new ViewModel and used that to populate the responses.
[HttpPost]
public ActionResult ViewQuestion([Bind(Include = "QuestionId, Answer, UserId")] ResponseViewModel responseViewModel)
{
Response re = new Models.Response();
re.Answer = responseViewModel.Answer;
re.UserId = responseViewModel.UserId;
re.QuestionId = responseViewModel.QuestionId;
re.DateStamp = System.DateTime.Now;
db.Responses.Add(re);
db.SaveChanges();
return RedirectToAction("ViewQuestion");
}
Thanks for your input as your comments got the old head working again. Thanks!
Your PostResponse action, or method specifies an ActionResult as a return type, but does not actually return anything. You can resolve this by changing it from ActionResult to void
try
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostResponse([Bind(Include = "UserId,QuestionID,Answer,Source,Status,DateStamp")] Response response)
{
if (ModelState.IsValid)
{
db.Responses.Add(response);
db.SaveChanges();
}
else{
return View("Error");
}
}

Remote validation work but form not post

I am using Remote validation on two field Email and CNIC.Remote Validation work proper but when i clik on submit button form not post.When i remove remote validation on both of fileds form post the data.
Model
Public class VMModel{
[Remote("Function","Controller",ErrorMessage = "The CNIC already exists")]
public string CNIC { get; set; }
[Remote("Function2", "Controller", ErrorMessage = "The Email already exists")]
public string Email { get; set; }
}
Controller
public JsonResult Function2(string Email)
{
bool IsExist = true;
if (Membership.GetUser(Email) != null)
{
IsExist = false;
}
return Json(IsExist, JsonRequestBehavior.AllowGet);
}
public JsonResult Function(string CNIC)
{
bool IsExist = true;
if (GetUserByCNIC(CNIC) != null)
{
IsExist = false;
}
return Json(IsExist, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Create(VMModel model)
{
return View(model);
}
View Code
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
<%using (Html.BeginForm("Create", "Controller", FormMethod.Post, new { enctype = "multipart/form-data"}))
{ %>
<fieldset>
<div class="inner_left">
<div class="editor-label">
<%: Html.LabelFor(m => m.Email)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Email)%>
<%:Html.ValidationMessageFor(m => m.Email)%>
</div>
<div class="clear"></div>
<div class="editor-label">
<%: Html.LabelFor(m => m.CNIC)%>
</div>
<div class="editor-field">
<%: Html.EditorFor(m => m.CNIC)%>
<%:Html.ValidationMessageFor(m => m.CNIC)%>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<p style="text-align:left;margin-left: auto;margin-right: auto;width: 400px;">
<input type="submit" class="hrbutton" value="Create" />
</p>
</fieldset>
<% } %>

asp.net mvc using ajax, but the callback won't redirect

I'm using ajax for two different partial views in the same parent view. The ajax request is submitted successfully, and the OnSuccess() function is called, but the page won't redirect. Here's my code. I've made sure that the returnurl is an absolute address.
VIEW:
#{
ViewBag.Title = "Log in/Register";
}
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
</hgroup>
#section CustomScripts {
<script type ="text/javascript">
function OnSuccess(){
var returnUrl = #ViewBag.ReturnUrl
window.location = returnUrl
}
</script>
}
<section id="loginForm">
#{
if(!WebSecurity.IsAuthenticated){
<h2>Use a Creative Works account to log in.</h2>
#Html.Action("_LoginPartial", new {returnUrl = ViewBag.ReturnUrl })
}
}
</section>
<section id ="RegisterForm">
#{
if(!WebSecurity.IsAuthenticated){
<span>Don't have an account? Make one!</span>
#Html.Action("RegisterPartial", new { returnUrl = ViewBag.ReturnUrl })
}
}
</section>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
PartialView for login:
#{
ViewBag.Title = "LoginPartial";
}
#using (Ajax.BeginForm("_LoginPartial", new {returnUrl = ViewBag.ReturnUrl},
new AjaxOptions(){UpdateTargetId = "loginForm",
InsertionMode = InsertionMode.Replace, OnSuccess = "OnSuccess"
})) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</li>
<li>
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe, new { #class = "checkbox" })
</li>
</ol>
<input type="submit" value="Log in" />
</fieldset>
}
and the controller:
[AllowAnonymous]
public ActionResult _LoginPartial(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return PartialView(new LoginModel());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult _LoginPartial(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return PartialView();
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return PartialView(model);
}
EDITS:
Parent View Controller
[AllowAnonymous]
[DisableCache]
public ActionResult Login(string returnUrl ="/")
{
var path = VirtualPathUtility.ToAbsolute(returnUrl);
var url = new Uri(Request.Url, path).AbsoluteUri;
ViewBag.ReturnUrl = url;
return View();
}
The problem was me accessing viewbag directly in my javascript. The answer was to replace my javascript with this.
#section CustomScripts {
<script type ="text/javascript">
function OnSuccess() {
var returnUrl = #Html.Raw(Json.Encode(ViewBag.ReturnUrl))
window.location = returnUrl;
}
</script>
}

Resources