Trailing dot trouble while saving MVC 5 - entity-framework

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>

Related

ASP.NET MVC How to use User's data after they log in

If I have a form for creating a holiday request:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal" style=" position:relative; top:20px;border-radius: 0px; border-color: #F47B20; border-style: solid; border-width: 5px; background-repeat: no-repeat; background-position: right; padding: 60px; background-size: contain; background-color:white ">
<h2 align="center">Holiday Request Form</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.EmployeeID, "Employee Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("EmployeeID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartDate,"Start Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate, "Start Date",new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FinishDate, "Finish Date",htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FinishDate, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
#Html.ValidationMessageFor(model => model.FinishDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HoursTaken,"Hours Requested", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HoursTaken, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HoursTaken, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(
model => model.Comments,
new { placeholder = "Enter Dates and how many Hours per Date Here.", style = "width: 400px; height: 200px;" })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-warning" />
</div>
</div>
</div>
}
But Instead of an Employee selecting their name of a dropdown list, The input will be based from the log in.
I already figured out how to grab the Employees Id from the log in but I am unsure how to use it in a form.
This is how I grabbed it using the controller which works for other aspects of my app
string name = Session["Name"].ToString();
var EmployeeIDCatch = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID);
Controller:
public ActionResult Create()
{
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName");
return View();
string name = Session["Name"].ToString();
var EmployeeIDCatch = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID);
}
// POST: HolidayRequestForms/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RequestID,EmployeeID,StartDate,FinishDate,HoursTaken,Comments,YearCreated,MonthCreated,DayCreated,YearOfHoliday,Approved")] HolidayRequestForm holidayRequestForm)
{
if (ModelState.IsValid)
{
db.HolidayRequestForms.Add(holidayRequestForm);
db.SaveChanges();
SendMailToAreaManager();
SendMailToManager();
return RedirectToAction("Index","Calendar");
}
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName", holidayRequestForm.EmployeeID);
return View(holidayRequestForm);
}
First remove the following code from your html form:
<div class="form-group">
#Html.LabelFor(model => model.EmployeeID, "Employee Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("EmployeeID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
Now update your Create POST method as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RequestID,StartDate,FinishDate,HoursTaken,Comments,YearCreated,MonthCreated,DayCreated,YearOfHoliday,Approved")] HolidayRequestForm holidayRequestForm)
{
if (ModelState.IsValid)
{
string name = Session["Name"].ToString();
var employeeID = db.Employees.Where(s => s.Email.Equals(name))
.Select(s => s.EmployeeID).FirstOrDefault();
holidayRequestForm.EmployeeID = employeeID;
db.HolidayRequestForms.Add(holidayRequestForm);
db.SaveChanges();
SendMailToAreaManager();
SendMailToManager();
return RedirectToAction("Index","Calendar");
}
return View(holidayRequestForm);
}

I am new to MVC 5, I want to bind dropdownlistfor from master table and entityframework6

I am new to MVC 5, I want to bind dropdownlistfor from master table and entityframework6. I am creating Building page and on that page I want to bind list of branches under which building will come.
To fetch data I am using EntityFramework 6.
In the Controller Page:
private DBEntities db = new DBEntities();
public ActionResult Load()
{
ViewBag.PlusOrMinus1 = new SelectList(db.t_CartesianSymbol, "CartId", "CartesianSymbol");
return View();
}
And in the View Page:
<div class="row poc-row-alert">
<div class="col-md-3">
#Html.LabelFor(model => model.PlusOrMinus1, "Operator 1", htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-9">
#Html.DropDownList("PlusOrMinus1", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PlusOrMinus1, "", new { #class = "text-danger" })
</div>
</div>
Please, do the needful changes.

Using foolproof and requiredif to validate a string field

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.

Cannot add new role in MVC5 Microsoft.AspNet.Identity.EntityFramework.IdentityRole?

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();
}
}

Upload in MVC4, got 2 parameters in my action but file is empty

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