I have a problem with update data in Asp.net MVC 5 with Razor Engine .
my Update code works fine but I have some problems with it . When I update Image , old image stays in Images folder. I want to delete old image if it changed . and I want to stay old image if it didn't change .
How can I do it ?
Thanks a lot for any help
I don't know how write if statement for this :/
CarouselRepositories.cs
public bool Update(NP1.Models.Carousel entity, bool autoSave = true)
{
try
{
db.Carousels.Attach(entity);
db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
Admin controller
[HttpGet]
public ActionResult EditCarousel(int id)
{
var load = db.Carousels.Find(id);
return View(load);
}
[HttpPost]
public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
{
CarouselRepositories blCarousel = new CarouselRepositories();
string path = "";
var fileName = "";
var rondom = "";
if (UploadImage != null)
{
fileName = Path.GetFileName(UploadImage.FileName);
rondom = Guid.NewGuid() + fileName;
path = System.IO.Path.Combine(
Server.MapPath("~/Images/Carousel"), rondom);
carousel.CarouselImage = rondom;
}
if (ModelState.IsValid)
{
UploadImage.SaveAs(path);
carousel.CarouselImage = rondom;
if (blCarousel.Update(carousel))
{
return JavaScript("alert('Carousel slide added');");
}
else
{
return JavaScript("alert('didn't add');");
}
}
else
{
return JavaScript("alert('Error');");
}
}
EditCarousel.cshtml:
#model NP1.Models.Carousel
#{
ViewBag.Title = "EditCarousel";
Layout = "~/Views/Admin/AdminLayout.cshtml";
}
#using (Html.BeginForm("EditCarousel", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.CarouselID)
<div class="form-group">
#Html.LabelFor(model => model.CarouselSubject, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CarouselSubject)
#Html.ValidationMessageFor(model => model.CarouselSubject)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CarouselInfo, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CarouselInfo)
#Html.ValidationMessageFor(model => model.CarouselInfo)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CarouselImage, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.CarouselImage)*#
#Html.ImageFor(model => model.CarouselImage, new {width="300"},"","Images","Carousel")
#Html.Upload("UploadImage")
#Html.HiddenFor(model => model.CarouselImage)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Updated Amin Controller :
[HttpPost]
public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
{
CarouselRepositories blCarousel = new CarouselRepositories();
string path = "";
var fileName = "";
var rondom = "";
if (UploadImage != null)
{
fileName = Path.GetFileName(UploadImage.FileName);
rondom = Guid.NewGuid() + fileName;
path = System.IO.Path.Combine(
Server.MapPath("~/Images/Carousel"), rondom);
carousel.CarouselImage = rondom;
}
else
{
fileName = carousel.CarouselImage;
path = System.IO.Path.Combine(
Server.MapPath("~/Images/Carousel"), fileName);
}
if (ModelState.IsValid)
{
UploadImage.SaveAs(path); // I got error in this line
carousel.CarouselImage = rondom;
if (blCarousel.Update(carousel))
{
return JavaScript("alert('Carousel slide added');");
}
else
{
return JavaScript("alert('didn't add');");
}
}
else
{
return JavaScript("alert('Error');");
}
}
Assuming you want to delete the current file if the value of UploadImage is not null in the POST method, then you can use the System.IO.File.Delete method
private const string _ImagesPath = "~/Images/Carousel";
[HttpPost]
public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
{
if (ModelState.IsValid)
{
CarouselRepositories blCarousel = new CarouselRepositories();
if (UploadImage != null)
{
// Delete exiting file
System.IO.File.Delete(Path.Combine(Server.MapPath(_ImagesPath), carousel.CarouselImage));
// Save new file
string fileName = Guid.NewGuid() + Path.GetFileName(UploadImage.FileName);
string path = Path.Combine(Server.MapPath(_ImagesPath), fileName);
UploadImage.SaveAs(path)
carousel.CarouselImage = fileName;
}
if (blCarousel.Update(carousel))
{
....
}
else
{
....
}
}
else
{
....
}
}
Related
I'm having the problem where I get 0 value return from my view bag Drop-down list. I don't have any problem for displaying list to my drop-down but when I submit the form, both of my drop down return 0 values to my controller. even, I selected the list.
Here is my code for Add controller.
public ActionResult Add()
{
List<City> lstcCities = db.Cities.ToList();
lstcCities.Insert(0, new City { Id = 0, Name = "Choose City" });
List<County> lstCounties = db.Counties.ToList();
lstCounties.Insert(0, new County { Id = 0, Name = "Choose County" });
ViewBag.CityId = new SelectList(lstcCities, "Id", "Name");
ViewBag.CountyId = new SelectList(lstCounties, "Id", "Name");
var category = db.Categories.ToList();
var viewModel = new AdsViewModel
{
Category = category,
};
return View("Add", viewModel);
}
Here is my view code
<div class="form-group">
#Html.LabelFor(m => m.Ads.City.Id)
#Html.DropDownList("CityId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Ads.CityId, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Ads.County.Name)
#Html.DropDownList("CountyId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Ads.CountyId, "", new { #class = "text-danger" })
</div>
Here is my post action.
[HttpPost]
public ActionResult Add(Ads ads, IEnumerable<HttpPostedFileBase> images,
HttpPostedFileBase ImageFile)
{
//Ensure model state is valid
if (ModelState.IsValid)
{
//check if images is null
if (images != null)
{
var imageList = new List<AdsImage>();
foreach (var image in images) //Loop for images for multiple uploading.
{
using (var br = new BinaryReader(image.InputStream))
{
var data = br.ReadBytes(image.ContentLength);
var img = new AdsImage { AdsId = ads.Id };
img.ImageData = data;
imageList.Add(img);
}
}
ads.AdsImage = imageList;
}
//Upload poster
////Add image to database
string fileName = Path.GetFileNameWithoutExtension(ImageFile.FileName);
string extension = Path.GetExtension(ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
ads.Poster = "/Images/Ads_Image/" + fileName;
fileName = Path.Combine(Server.MapPath("/Images/Ads_Image/"), fileName);
ImageFile.SaveAs(fileName);
ViewBag.CityId = new SelectList(db.Cities, "Id", "Name", ads.CityId);
ViewBag.CountyId = new SelectList(db.Counties, "Id", "Name", ads.CountyId);
var userID = User.Identity.GetUserId();
ads.ApplicationUserId = userID;
ads.PostDate = DateTime.Now;
db.Adses.Add(ads);
db.SaveChanges();
}
}
Anyone knows how to fix this problem or can help me with this problem
Thank you in advance for any helps.
Hello i'm trying to consume rest web service from jee application to asp.net
when i copy the url it work perfectly but when i excute it from the app the url changes specifically the dates .
Example of the erorr :
22:03:32,629 WARN [org.jboss.resteasy.core.ExceptionHandler] (default
task-69) failed to execute: javax.ws.rs.NotFoundException: Could not
find resource for full path:
http://localhost:18080/PiDev-web/rest/absence/creates/aaaqwqwq/07/11/2018%2000:00:00/07/11/2018%2000:00:00
[JEE app]
here's my service :
#Override
public void createAbsence(Absence e) {
EmployeService ee =new EmployeService();
ConnectedUser emp = em.find(ConnectedUser.class, 1);
System.out.println("Service Done 0 !!!");
e.setIdEmploye(emp.getId());
e.setLogin(emp.getLogin());
e.setJustifie(false);
//e.setEmploye(UserConnected);
em.persist(e);
System.out.println("Service Done !!!");
}
and myBean:
#POST
#Path("/creates/{cause}/{dd}/{df}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response serviceCreates(#PathParam(value = "cause") String cause,#PathParam(value = "dd") String dd,#PathParam(value = "df") String df) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dated=new Date();
Date datef=new Date();
try {
dated = dateFormat.parse(dd);
datef = dateFormat.parse(df);
System.out.println(dated);
} catch (ParseException e) {
e.printStackTrace();
}
return Response.status(Status.ACCEPTED).entity(absenceService.createAbsence(new Absence(cause,dated,datef))).build();
}
[Asp.Net app]
Controller :
[HttpPost]
public ActionResult Create(absence abs)
{
try
{
HttpClient Client = new System.Net.Http.HttpClient();
Console.WriteLine(abs.dateDebut);
Client.BaseAddress = new Uri("http://localhost:18080/PiDev-web/rest/absence/");
Client.PostAsJsonAsync<absence>("creates/" + abs.cause + "/" + abs.dateDebut + "/" + abs.dateFin, abs);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
and my view :
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/backLayout.cshtml";
}
#model ProjectWeb.Models.absence
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add Absence</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.cause, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cause, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cause, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateDebut, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateDebut, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateDebut, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateFin, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateFin, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateFin, "", new { #class = "t-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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
i'm not familiar with date formats so if you are familiar please help me
The problem in your url that you use slash to separate year, month and day. Actually url use slash to separate part of path, so you have to not use slash except separate element of path.
For sending date it's better to use ISO format. Long story short you write date from biggest to lowest values and separate them using dash (year-month-dayThour:minutes:seconds) example
date time 2018-11-07T22:30:33
only date 2018-11-07
Rewrite your resource like this:
#POST
#Path("/creates/{cause}/{dd}/{df}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response serviceCreates(#PathParam(value = "cause") String cause,#PathParam(value = "dd") LocalDate dd,#PathParam(value = "df") LocalDate df) {
return Response.status(Status.ACCEPTED).entity(absenceService.createAbsence(new Absence(cause,dd,df))).build();
}
and try to invoke:
http://localhost:18080/PiDev-web/rest/absence/creates/aaaqwqwq/2018-11-07/2018-11-07
I am new in MVC asp.net i am developing a project where i want to add floors sequence wise. Want to start sequence from 0.
Message=LINQ to Entities does not recognize the method 'NTB.Floor LastOrDefault[Floor](System.Linq.IQueryable1[NTB.Floor], System.Linq.Expressions.Expression1[System.Func`2[NTB.Floor,System.Boolean]])' method, and this method cannot be translated into a store expression.
Controller:
public ActionResult Create(int id)
{
var cfloorno = 0;
//if (bid > 0)
//{
var lastfloor = db.Floors.Last(x => x.BuildingId == id);
if (lastfloor != null)
{
cfloorno = lastfloor.FloorNo.GetValueOrDefault() + 1;
}
//}
var building = db.Buildings.ToList();
ViewBag.Building = building;
var type = db.FloorTypes.ToList();
ViewBag.Type = type;
ViewBag.CurrentFloor = cfloorno;
ViewBag.buildingid = id;
return View();
}
[HttpPost]
public ActionResult Create(Floor f)
{
using (db)
{
db.Floors.Add(f);
db.SaveChanges();
}
return RedirectToAction("List");
}
View:
<input type="hidden" name="BuildingId" value="#ViewBag.buildingid" />
<div class="row">
<label class="col-sm-2 control-label">Floor #</label>
<div class="col-sm-10">
<input class="form-control" name="FloorNo" value="#ViewBag.CurrentFloor" disabled type="number">
#Html.ValidationMessageFor(model => model.FloorNo)
</div>
</div>
My Date control is always empty when the page loads.
Why is that?
There is data in the database for that control.
<div class="form-group">
#Html.LabelFor(model => model.StartDate, new { #class = "control- label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.StartDate, new { type = "Date" })
#Html.ValidationMessageFor(model => model.StartDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.EndDate, new { type = "Date" })
#Html.ValidationMessageFor(model => model.EndDate)
</div>
</div>
As noted by #Coulton, make sure you're actually populating your model's StartDate and EndDate properties on your controller before rendering the page. Also if you use the [DataType(DataType.Date)] flag on your class you could discard the TextBoxFor helper and instead used the EditorFor helper.
Examples for populating the data attributes before a Create or an Edit view (Which seems to be the view you're trying to build there):
Controller.cs, ganho.Data is a DateTime attribute with a [DataType(DataType.Date)] flag
[HttpGet]
public ActionResult Edit(int? id)
{
// Omitted code
var result = from ganho in db.Ganhos
where ganho.GanhoID == id.Value
where ganho.Usuario.Id == user.Id
select new GanhoEditViewModel
{
GanhoID = ganho.GanhoID,
Valor = ganho.Valor,
Comentario = ganho.Comentario,
Data = ganho.Data,
Descricao = ganho.Descricao,
Tipo = ganho.Tipo
};
if (result.Count() < 1)
{
// 404, no such item exists
return HttpNotFound();
}
return View(result.Single());
}
Edit.chtml
<!-- Hidden Code, not relevant to the question -->
<div class="form-group">
#Html.LabelFor(model => model.Data, htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.Data, new { htmlAttributes = new { #class = "form-control", #id = "dataInput"} })
#Html.ValidationMessageFor(model => model.Data, "", new { #class = "text-danger"})
</div>
</div>
In case you're setting up for a Create view, you can initialize the field like this:
Controller.cs, ganho.Data is my DateTime attribute which the user will display a placeholder data.
[HttpGet]
public ActionResult Create()
{
var model = new Ganho()
{
// ...
Data = DateTime.Now, // Using the current date and time as a placeholder
// ...
};
return View(model);
}
Please note that in all examples I'm using Strongy Typed views!
I had this error when use upload file with razor page :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
the error occurred here
var uploadedFile = Request.Files[0];
Controller:
[HttpPost]
public ActionResult Create(Category category)
{
if (ModelState.IsValid)
{
var fileSavePath = "";
var fileName = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("../../Uploads/" + fileName);
uploadedFile.SaveAs(fileSavePath);
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
View:
#using (Html.BeginForm("Create", "Category", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
#Html.LabelFor(model => model.Path)
</div>
<div class="editor-field create-Bt3">
#FileUpload.GetHtml(
initialNumberOfFiles: 1,
allowMoreFilesToBeAdded: false,
includeFormTag: false,
uploadText: "Upload")
</div>
}
The error means, that the Request.Files collection does not contain any item.
You can check with the Count property for the number of files uploaded:
if (Request.Files.Count > 0) {
var uploadedFile = Request.Files[0];
}
Check with fiddler what the browser is sending - maybe its an issue with the FileHelper