I have the following fields in my data model:
public bool JointAccount { get; set; }
[RequiredIf("JointAccount", "true", ErrorMessage = "Please select a Title")]
public string JointAccountTitle { get; set; }
[RequiredIf("JointAccount", "true", ErrorMessage = "Please enter first name")]
public string JointAccountFirstName { get; set; }
I have the following in my views:
<div class="form-group">
#Html.Label("Joint Account?", htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="checkbox">
#Html.EditorFor(model => model.JointAccount)
#Html.ValidationMessageFor(model => model.JointAccount, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.Label("Title", htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
<select required style="width:100%;height:35px;border-radius:4px;padding-left:10px;" id="JointAccountTitle" name="JointAccountTitle" class="form-control input required">
<option value="">Please Select Title</option>
<option value="Mr">Mr</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Fr">Fr</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
<option value="Rev">Rev</option>
<option value="Sr">Sr</option>
<option value="Br">Br</option>
</select>
#Html.ValidationMessageFor(model => model.JointAccountTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("First Name", htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.JointAccountFirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.JointAccountFirstName, "", new { #class = "text-danger" })
</div>
</div>
I am trying to ensure that data is entered here if the jointaccount checkbox is filled but it does not seem to be throwing any validation error on the textbox only on the dropdown list for the title, any ideas here?
Your creating the <select> element manually and not adding the necessary data-val-* attributes required by jquery.validate.unobtrusive.js to add the rules for to jquery.validate.js so you could never get jquery validation for the <select> (note that the required attribute is HTML5 validation, not jquery validation).
If your claiming that your getting validation on the JointAccountTitle property (dropdownlist), but not on the JointAccountFirstName (textbox), it means that jquery client side validation is not even being triggered. The most likely cause is that you do not have the correct scripts loaded, or they are loaded in the wrong order. You need to have
jquery-{version}.js
jquery.validate.js
jquery.validate.unobtrusive.js
mvcfoolproof.unobtrusive.js
The to get jquery validation for the select list, you need to add the relevant data-val- attributes to you manual html, or better, generate you dropdownlist using the DropDownListFor() method
#Html.DropDownListFor(m => m.JointAccountTitle, Model TitleList, "Please select title", new { # class="form-control input })
where TitleList is an IEnumerable<SelectListItem> property in your view model containing the values for the options
I recently ran into the same issue. Try replacing the .EditorFor() with a .TextBoxFor():
#Html.TextBoxFor(model => model.JointAccountFirstName, new { htmlAttributes = new { #class = "form-control" } })
Not sure why this is a problem for Foolproof, but it worked for me.
Related
I have this model item to modify and save in MVC 5.
(.NET Framework 4.6.1)
#using (Ajax.BeginForm("Edit", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "wrapperViews" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>EQUIPMENT - #ViewBag.EQP_ID</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.OPERATIONID)
<div class="form-group">
#Html.LabelFor(model => model.DESCRIPTION, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.DESCRIPTION, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DESCRIPTION, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TYPE, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.TYPE,
new SelectList(Model.EquipmentTypes, "CodeType", "DescriptionType"),"", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TYPE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div style="width:500px;margin-top:15px">
<div style="width:120px; float:left;margin-left:30px">
<input type="submit" value="Save" class="btn btn" />
</div>
<div style="width:120px; float:left;">
#Ajax.ActionLink("Back to the list", "Index", "Equipment", new { id = Model.OPERATIONID }, new AjaxOptions()
{
OnSuccess = "OpenEquipment"
})
</div>
</div>
</div>
</div>
The problem is that entity field to modify contains dot in the name, like that:
http://localhost:62396/controllername/Edit/SUPREP.ABL
When I submit the form, it comes error
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Detailed Error Information:
Module IIS Web Core
Notification MapRequestHandler
Handler StaticFile
Error Code 0x80070002
Requested URL http://localhost:62396/controller/Edit/SUPREP.ABL
Physical Path C:\projectname\controller\Edit\SUPREP.ABL
I tried anything I could but I didn't solved my trouble.
Any help would be appreciated.
Just Solved. Need to add to RouteConfig.cs the following line:
routes.AppendTrailingSlash = true;
And everything works. Thank you.
The problem is with your URL. IIS thinks that you're requesting for a file with extension ".ABL". You can simply add a trailing / to make it act like a route.
e.g.: http://localhost:62396/controllername/Edit/SUPREP.ABL/
Also make sure you've enabled double escaping by adding this to web.config :
<security>
<requestFiltering allowDoubleEscaping="true"/>
</security>
I get the following error when I try to add a Schedule.
The column name 'Doctor_id' is specified more than once in the SET clause or column list of an INSERT. A column cannot be assigned more than one value in the same clause. Modify the clause to make sure that a column is updated only once. If this statement updates or inserts columns into a view, column aliasing can conceal the duplication in your code.
Here is my schedule model
[Table("Schedule")]
public class Schedule
{
public int Id { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeSpan StartTime { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeSpan EndTime { get; set; }
public bool Booked { get; set; }
public int Doctor_id { get; set; }
//public virtual Doctor Doctor { get; set; }
}
Here is my controller:
public ActionResult CreateSchedule(Schedule schedule)
{
TimeSpan startTime = schedule.StartTime;
TimeSpan endTime = schedule.EndTime;
db.Schedules.Add(schedule);
db.SaveChanges();
}
This is the form
<div class="form-horizontal">
<h4>Schedule</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<input type="hidden" name="Doctor_id" value="#Session["doctorid"]" />
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control date" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
I have a hidden input name Doctor_id with value for the create form.
Please help me with this, thanks.
I want to show Gender Male Radio Button and Female Radio button on create and on Edit the selected radio button if male then male should be selected if Female then female should be checked.
Model
[Table("tblUserData")]
public class test
{
[Key]
public int Id { get; set; }
public string FullName { get; set; }
public Nullable<bool> Gender { get; set; }
}
Create View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>test</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.FullName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FullName)
#Html.ValidationMessageFor(model => model.FullName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Gender)
#Html.ValidationMessageFor(model => model.Gender)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
How do I replace the
#Html.EditorFor(model => model.Gender)
With
#Html.RadioButtonFor(model=>model.Gender)
It asks for one more parameter where do I get it from as its a Bit in sql if its 0 then Gender is Male if 1 then Female.
Same I want to do it for edit so that user can see the Gender and update it through radio buttons.
Assuming your razor view is strongly typed to your class,test
#model test
#using (Html.BeginForm())
{
#Html.RadioButtonFor(model => model.Gender, true)
<span>Male</span>
#Html.RadioButtonFor(model => model.Gender, false)
<span>FeMale</span>
<input type="submit" />
}
For your edit view, the same code will work as long as you are sending a valid object of test to your view. Based on the value on the Gender property, it will select the corresponding radio button.
public ActionResult Edit(int id)
{
var vm = yourSbContext.tests.FirstOrDefault(s=>s.Id==id);
if(vm!=null)
{
return View(vm);
}
// to do : Return a Not found/404 response/view
}
I add 3 roles using my MVC application before. Now I cant add new role. When I debug I can see new role Id but the Role name is empty. How can I solve this problem?
I have 3 roles at the moment. User, Admin, Sales. Now I want to add Account role and cannot add.
CONTROLLER
// POST: /Roles/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
{
Name = collection["RoleName"]
});
context.SaveChanges();
ViewBag.ResultMessage = "Role created successfully !";
return RedirectToAction("Index");
}
catch
{
return View();
}
}
CSHTML
#model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
<div class="container body-content">
#{
ViewBag.Title = "Create";
}
<h2>Create Role</h2>
#Html.ActionLink("List Roles", "Index") | #Html.ActionLink("Manage User Role", "ManageUserRoles")
<hr />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<p>
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
</p>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
}
</div>
You should only use viewModels in your view, but as you are using your view and object now, you should adjust your controller the following to use mvc roleManager (much easier):
// POST: /Roles/Create
[HttpPost]
public ActionResult Create(IdentityRole role)
{
try
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
roleManager.Create(role)
context.SaveChanges();
ViewBag.ResultMessage = "Role created successfully !";
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I'm trying to upload a file to a directory. The following code worked for me
CONTROLLER
[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
//string path = #"C:\Users\thomas\Desktop";
if (uploadFile != null)
{
string filePath = Path.Combine(Server.MapPath("/files"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return RedirectToAction("Index");
}
HTML PAGE
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="/Post/Index" method="post" enctype="multipart/form-data">
<label for="uploadFile">Upload file: </label>
<input name="uploadFile" id="uploadFile" type="file" />
<input value="uploadFile" type="submit" />
</form>
Now i'm trying to implement this in a function where i create a message which is created by a model that is containing a message and an item class. When i submit the form the model is passed to my savecontroller but the file is null in my parameter controller.
HTML PAGE
Create new message
#model GeoCitytroopers.Models.MessageItemModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Event</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Message.MessagePicture)
</div>
<div>
<label for="uploadFile">Upload file: </label>
<input name="uploadFile" id="uploadFile" type="file" />
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Message.MessagePicture)
#Html.ValidationMessageFor(model => model.Message.MessagePicture)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Item.ItemTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item.ItemTitle)
#Html.ValidationMessageFor(model => model.Item.ItemTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Item.ItemDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item.ItemDescription)
#Html.ValidationMessageFor(model => model.Item.ItemDescription)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
CONTROLLER
[HttpPost]
public ActionResult Create(HttpPostedFileBase uploadFile, MessageItemModel ViewModel)
{
if (ModelState.IsValid)
{
Utility ut = new Utility();
Item viewItem = ViewModel.Item;
Message viewMessage = ViewModel.Message;
if (uploadFile != null)
{
string filePath = Path.Combine(Server.MapPath("/files"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
//ADD USER TO ITEM
viewItem = ut.AddUserToItem(viewItem);
//ADD ITEM
viewItem.ItemCreateddate = DateTime.Now;
//ADD DISTRICT TO ITEM
viewItem.DistrictID = ut.GetUserDistrict();
db.Items.Add(viewItem);
//ADD LINK
viewMessage.Item = viewItem;
db.Messages.Add(viewMessage);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ViewModel);
}
How can i pass the uploading file to my controller?
Thanks in advance!
You forgot set the correct enctype to the form. You cannot upload files without that:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) {
...
}
Now the upload will work and your uploadFile parameter will not be null.
My initial guess is that the you created using Html helper doesn't have the necessary encrypt on it.
try using
using(#Html.BeginForm("action-name","controller-name",
FormMethod.Post, new { enctype="multipart/form-data"}){
}
with appropriate values for action-name and controller-name