I'm using ASP.NET C# with entity framework and I'm trying to upload image for a profile and display it.
Here is the relevant part of the View file (Manage.cshtml)
<input type="file" name="form-register-photo" id="form-register-photo" disabled>
Here is the relevant part of the Controller file (Manage.cs)
[HttpPost]
public ActionResult Manage(ManageViewModel manageviewmodel,HttpPostedFileBase upload)
{
TheFoodyContext db = new TheFoodyContext();
User user_to_update = db.Users.SingleOrDefault(s => s.email == manageviewmodel.Email);
if (ModelState.IsValid)
{
if (user_to_update != null && (upload != null && upload.ContentLength > 0))
{
var fileName = Path.GetFileName(upload.FileName);
var path = Path.Combine(Server.MapPath("~/FOODY"), fileName);
user_to_update.email = manageviewmodel.Email;
user_to_update.fname = manageviewmodel.FirstName;
user_to_update.lname = manageviewmodel.LastName;
user_to_update.phone = manageviewmodel.Phone;
user_to_update.photo = path;
user_to_update.address = manageviewmodel.Address;
user_to_update.city = manageviewmodel.City;
user_to_update.postcode = manageviewmodel.PostCode;
user_to_update.district = manageviewmodel.District;
user_to_update.user_type = manageviewmodel.UserType;
user_to_update.status = manageviewmodel.Status;
db.SaveChanges();
return RedirectToAction("Manage");
}
}
return View(manageviewmodel);
}
Within the above controller i have coded for other fields also. So I want to upload the picture among with them. That means from a single button click.
Here is my Model class (ManageViewModel.cs)
public class ManageViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Photo { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int PostCode { get; set; }
public string District { get; set; }
public string UserType { get; set; }
public string Status { get; set; }
}
But for this one photo uploading part did not work properly. So I really don't know how to manage this.
Entity Framework doesn't help you to literally upload an image.
From your code, you only just edit 1 record in Users in database, without actually upload the image to hosting drive.
For simple, you will need to have something like below to store the file in physically:
var path = Path.Combine(Server.MapPath("~/FOODY"), fileName);
upload.SaveAs(newSPath);
You didn't show exactly what is the result after this db.SaveChanges(); show I'm not sure whether your photo path getting any error. My suggestion is add in a try catch block and run the code in Debug, see what will you have in user_to_update.photo after db.SaveChanges();
Related
I have some code that is functioning oddly and was wondering if anyone else hase come across this issue.
I have a view model that collects data from a database via a stored procedure and a vb object (no I do not know vb this is legacy)
When I execute the program the data is collected as expected via the controller. When I debug it I can see all of my parameters populating with information. However when it comes to the view it says that the parameters are null. I have included my code
Models:
public class PersonIncomeViewModel
{
public string IncomeTypeDesc { get; set; }
public string IncomeDesc { get; set; }
public string Income { get; set; }
}
public class PersonIncomeListViewModel
{
public int? PersonId { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonIncomeListViewModel()
{
Incomes = new List<PersonIncomeListItem>();
}
}
public class PersonLookupViewModel : Queue.QueueViewModel
{
public int Action { get; set; }
public bool ShowAdvancedFilters { get; set; }
//Person Search Variables
[Display(Name = #"Search")]
public string SpecialSearch { get; set; }
[Display(Name = #"Person Id")]
public int? PersonId { get; set; }
[Display(Name = #"Full Name")]
public string FullName { get; set; }
[Display(Name = #"SSN")]
public string SSN { get; set; }
public string AddressStatus { get; set; }
public string EmploymentStatus { get; set; }
public PersonIncomeViewModel Income { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonLookupViewModel()
{
Income = new PersonIncomeViewModel();
Incomes = new List<PersonIncomeListItem>();
}
}
Controller:
public ActionResult _Income(int id)
{
var vm = new PersonLookupViewModel();
var personManager = new dtPerson_v10_r1.Manager( ref mobjSecurity);
//var person = personManager.GetPersonObject((int)id, vIncludeIncomes: true);
var person = personManager.GetPersonObject(id, vIncludeIncomes: true);
var look = JsonConvert.SerializeObject(person.Incomes);
foreach (dtPerson_v10_r1.Income income in person.Incomes)
{
if (income.IncomeType_ID == 0)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Unknown",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 1)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Alimony",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 2)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Child Support",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
}
return PartialView(vm);
}
View:
#using dtDataTools_v10_r1
#using ds_iDMS.Models.Person
#model ds_iDMS.Models.Person.PersonLookupViewModel
#{
var format = new dtDataTools_v10_r1.CustomFormat();
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
}
using (Html.DSResponsiveRow(numberOfInputs: ExtensionMethods.NumberOfInputs.TwoInputs))
{
using (Html.DSCard(ExtensionMethods.Icon.CustomText, iconInitials: newInitials, color: ExtensionMethods.Colors.PrimaryBlue))
{
<div>#Model.Income.IncomeTypeDesc</div>
<div>#Model.Income.IncomeDesc</div>
<div>#Model.Income.Income</div>
}
}
There are some extensions that we have built but they are irrelevant to the issue
The line that errors out is this one:
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
Which drives all of the extension methods on the view and as I run the debugger over it all of the parameters read null, however like I said when I run the debugger and check them in the controller they are populated properly.
Sorry about the long post but I wanted to ensure all the detail was there
This is how to pass the Object model to your Partial View
return PartialView("YourViewName", vm);
or using the Views path
return PartialView("~/YourView.cshtml", vm);
EDIT
Try starting your Action Method like this
var vm= new Person();
vm.PersonLookupViewModel = new PersonLookupViewModel();
Problem solved I had issues with some of my vb objects and had the vb person take a look at them and she fixed them.
Thank you for all the help
EDIT
What had to happen is the vb object had to be re-written and my logic was just fine as it was in the beginning. I marked the one response to my question as the answer because had it been in true MVC without vb objects attached to it, that would have worked perfectly
I am trying to create foreign key relationship using Entity Framework Code first approach.
I am creating 1-M relation b/w Vehicle and FileUpload (user can upload multiple images against one vehicle).
Problem: I always get FK value 0 and Vehicle navigation property null when saving file information.
Please help to understand what i am doing wrong?
Following are model classes with FK relation defined.
Vehicle model
public class Vehicle
{
public Vehicle()
{
FileUploads = new List<FileUpload>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<FileUpload> FileUploads { get; set; }
}
File Upload Model
public class FileUpload
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public int Vehicle Id { get; set; }
[ForeignKey("Vehicle Id")]
public virtual Vehicle Vehicle { get; set; }
[Required]
[MaxLength(250)]
[Display(Name = "File name")]
public string FileName { get; set; }
[Required]
public string FileName{ get; set; }
}
My post method inside controller
public HttpResponseMessage Post()
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
postedFile.SaveAs(filePath);
_saveToDB(postedFile.FileName);
}
return Request.CreateResponse(HttpStatusCode.Created);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
private void _saveToDB(string fileName)
{
FileUpload data = new FileUpload();
data.FileName = fileName;
db.FileUpload.Add(data); // here data.VehicleId is always 0 and navigation property null. At this stage Vehicle record has been already created in database.
db.SaveChanges();
}
data.VehicleId is 0 because data is a local variable you created.
FileUpload data = new FileUpload();
This is just C# code, and Entity Framework Code First has no knowledge about what VehicleId, these files need to be saved against.
Essentially, you need a VehicleId in your POST input or from the snippet that creates the Vehicle record. (to know the Vehicle againts which these images need to be uploaded)
Once you have the VehicleId, set it on the data object.
FileUpload data = new FileUpload();
data.FileName = fileName;
data.VehicleId = vehicleId; // get this from POST input or the snippet that created the Vehicle record.. so vehicle.Id
db.FileUpload.Add(data);
db.SaveChanges();
I can insert related child record in one shot when parent record is inserted. But if my child record is file then how can i insert and upload related child record (for file) in one shot. Where file will upload in different location not database.
Child file class :
public class File
{
public int Id { get; set; }
public string Name { get; set; }
public string RelativePath { get; set; }
public string MimeType { get; set; }
public int Size { get; set; }
public int QuestionId { get; set; }
public string ApplicationUserId { get; set; }
}
Parent item insertion code :
public ActionResult Create(QuestionCreateViewModel viewModel)
{
var question = new Question
{
Text = viewModel.Text,
QuestionType = viewModel.QuestionType,
Answer = viewModel.Answer,
Notes = viewModel.Notes,
CategoryId = viewModel.CategoryId,
Files = viewModel.Files // Also need to Upload
};
_questionRepository.Insert(question);
_questionRepository.Save();
return Json(null);
}
Now where i put my file upload code to upload files when insert parent and child data.
I solve it like this way : I used an extra function named ManageFiles(Request.Files) that upload all file then return list of uploaded files. So that when parent record insert it also upload it's child file and insert file record's in one shot.
public ActionResult Create(QuestionCreateViewModel viewModel)
{
var question = new Question
{
Text = viewModel.Text,
QuestionType = viewModel.QuestionType,
Answer = viewModel.Answer,
Notes = viewModel.Notes,
CategoryId = viewModel.CategoryId,
Files = ManageFiles(Request.Files)
};
_questionRepository.Insert(question);
_questionRepository.Save();
return Json(null);
}
private ICollection<File> ManageFiles(HttpFileCollectionBase fileCollection)
{
var files = new List<File>();
for (var index = 0; index < fileCollection.Count; index++)
{
if (fileCollection[index] == null || fileCollection[index].ContentLength <= 0)
{
continue;
}
if (UploadFile(Request.Files[index]))
{
var file = new File
{
Name = uploaded.FileName,
RelativePath = uploaded.FilePath + uploaded.FileName,
MimeType = uploaded.FileBase.ContentType,
Size = uploaded.FileBase.ContentLength
};
files.Add(file);
}
}
return files;
}
I have an ASP.NET Web Forms project which is using Readify-Neo4jClient and Neo4J Community 2.0.3, I'm getting a bug where a number stored in the database is changing its value when retrieved. Here is a picture of what’s in the database and what I can see in VS2013:
https://docs.google.com/file/d/0B6b_N7sDgjmvMVF5TFpaZXJmNFk/edit
The code to retrieve the user is as follows:
IEnumerable<SUser> FoundUsers = Neo4jGraphClient.Cypher.Match("(user:User)")
.Where((SUser user) => user.Email == UserName)
.Return(user => user.As<SUser>())
.Results;
Code to write to the database is as follows:
long DateTimeNow = DateTime.Now.Ticks;
SUser ss = new SUser
{
Id = UserCounter.SubmitAndCommitNewUser(),
DateOfBirth = DobDay.Text + "" + DobMonth.Text + "" + DobYear.Text,
Email = UserName.Text,
FirstName = FirstName.Text,
LastName = LastName.Text,
UserCreatedOn = DateTimeNow,
role = UType.ADMIN,
Status = UStatus.NEW
};
Neo4jReq.CreateSUser(ss);
......
public static SUser CrseateSUser(SUser NewUser)
{
//...
Neo4jGraphClient.Cypher
.Create("(user:User {NewUser})")
.WithParam("NewUser", NewUser)
.ExecuteWithoutResults();
existing = NewUser;
}
Class is as follows:
public class SUser
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DateOfBirth { get; set; }
public string Email { get; set; }
public UType role { get; set; }
public UStatus Status { get; set; }
public string pass { get; set; }
public string VerificationGUID { get; set; }
public long UserCreatedOn { get; set; }
public string UserNotes { get; set; }
}
Any ideas on whats causing this?
Right - I've got this replicating, this looks like a bug(?) in the way the Neo4j browser shows the data (both the current and older webadmin), so the data stored in Neo4j is correct, but it's getting 'rounded' (in a sense anyway) in the display, if you run the 'Get' query in the browser you get the '00' ending, this also happens in the old web admin:
http://localhost:7474/webadmin/
if you run the query in the 'Data Browser'.
However, if you run the query in the Console (http://localhost:7474/webadmin/#/console/) you'll get the correct results. Neo4jClient is giving you the right results, it's the browser that is wrong in this case.
I have a textarea where the user can type in input but if they create a newline in the text area I want it to be saved into to the database so it will appear with the newline. How do I do that?
It seems when the string is saved to the data base the /n is removed from the string.
Im using C# with EF6
gfdh
hgfd
hgfd
hgfd
;
This above is what shows in html but the physical display of it is just one line without the newlines
I have tried the br solution but its within the quotes and the br tag is useless if its within the tags. how do I get teh br tag to escape
public void SendMessageToUser(Message message)
{
var db = new database();
var list = db.Conversations.FirstOrDefault(c => c.UserAId == message.SenderId && c.UserBId == message.ReceiverId || c.UserAId == message.ReceiverId && c.UserBId == message.SenderId);
if (list != null)
{
message.ConversationId = list.ConversationId;
message.DateSent = DateTime.Now;
db.Messages.Add(message);
}
else
{
var conversation = new Conversation();
conversation.DateStarted = DateTime.Now;
conversation.ConversationStatusId = 1;
conversation.UserAId = message.ReceiverId;
conversation.UserBId = message.SenderId;
message.ConversationId = db.Conversations.Add(conversation).ConversationId;
message.MessageStatusId = 1;
message.DateSent = DateTime.Now;
db.Messages.Add(message);
}
db.SaveChanges();
}
public class Message
{
public int MessageId { get; set; }
public string Content { get; set; }
public DateTime DateSent { get; set; }
[ForeignKey("Conversation")]
public int ConversationId { get; set; }
public virtual Conversation Conversation { get; set; }
public int MessageStatusId { get; set; }
public virtual MessageStatus MessageStatus { get; set; }
[ForeignKey("Sender")]
public int SenderId { get; set; }
public virtual User Sender { get; set; }
[ForeignKey("Receiver")]
public int ReceiverId { get; set; }
public virtual User Receiver { get; set; }
}
html
#foreach (var m in Model.Messages)
{
<h3>#m.Sender.Username</h3>
<p>#m.DateSent.ToShortTimeString()</p>
#string.Format("{0}",m.Content);
#m.Content;
The text from the text area will be stored with newlines in the database. However if you want to display the text in HTML, you have to replace the newlines to <br /> tags and tell razor to not encode the HTML. You can do that by wrapping your text in a MvcHtmlString.
Here is an example of how you can achive that with a little HtmlHelper. Another way is to display your text using the #Html.Raw("Your text") HtmlHelper.
Also another posibility to display the line breaks is to use white-space: pre-line; so you don't need to allow HTML tags in your code which would make it more secure. (See here)