How can I get full info on update page - asp.net-core-mvc

I have an ASP.NET Core MVC project without Entity Framework.
When I click on the "update" button, I want to update page and make it does not become empty.
This is my view:
<div class="form-group">
<form asp-action="OdemeTurGuncelle">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
ID
<input asp-for="odemetur_id" class="form-control" />
<span asp-validation-for="odemetur_id" class="text-danger"></span>
</div>
<div class="form-group">
Ödeme Türü
<input asp-for="odemetur_adi" class="form-control" />
<span asp-validation-for="odemetur_adi" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
And my controller :
[HttpGet]
public IActionResult OdemeTurGuncelle()
{
return View();
}
[HttpPost]
public IActionResult OdemeTurGuncelle(OdemeTur odemeTur)
{
string constr = Genel.conString;
using (NpgsqlConnection con = new NpgsqlConnection(constr))
{
string query = "UPDATE odemeturleri SET odemetur_adi=#odemetur_adi WHERE odemetur_id=#odemetur_id";
using (NpgsqlCommand cmd = new NpgsqlCommand(query))
{
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#odemetur_id", odemeTur.odemetur_id);
cmd.Parameters.AddWithValue("#odemetur_adi", odemeTur.odemetur_adi);
cmd.ExecuteNonQuery();
con.Close();
}
}
// return View(ders);
return RedirectToAction("Index");
}
I can do it with Entity Framework, but I want to do it without EF

Related

My create.cshtml view page not opening ASP.NET Core 6 MVC application in Visual Studio 2022

I am creating an ASP.NET Core 6 MVC application, the application runs successfully but whenever I want to add an actor (based on project) the create view page does not work. It's showing an internal server error.
This is the error I get:
AspNetCoreGeneratedDocument.Views_Actors_Create.ExecuteAsync() in Create.cshtml
#model Actor
#{
ViewData["Title"] = "Add New Actor";
}
<div class="row text">
<div class="col-md-8 offset-2">
<p>
<h1>Add New Actor</h1>
The error is being highlighted on the ViewData line.
My create.cshtml
#model Actor
#{
ViewData["Title"] = "Add New Actor";
}
<div class="row text">
<div class="col-md-8 offset-2">
<p>
<h1>Add New Actor</h1>
</p>
<div class="row">
<div class="col-md-8 offset-2">
<form class="row" asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="mb-3">
<label asp-for="ProfilePictureURL" class="form-label"></label>
<input asp-for="ProfilePictureURL" type="text" class="form-control"/>
<span asp-validation-for="ProfilePictureURL" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="FullName" class="form-label"></label>
<input asp-for="FullName" type="text" class="form-control"/>
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Bio" class="form-label"></label>
<input asp-for="Bio" type="text" class="form-control"/>
<span asp-validation-for="Bio" class="text-danger"></span>
</div>
<div class="mb-3">
<input type="submit" value="Create" class="btn btn-outline-success float-end"/>
<a class="btn btn-outline-secondary" asp-action="Index"> Show All</a>
</div>
</form>
</div>
</div>
</div>
</div>
This is my ActorsController.cs:
using eTickets.Data;
using eTickets.Data.Services;
using Microsoft.AspNetCore.Mvc;
namespace eTickets.Controllers
{
public class ActorsController : Controller
{
private readonly IActorsService _service;
public ActorsController(IActorsService service)
{
_service = service;
}
public async Task<IActionResult> Index()
{
IEnumerable<Models.Actor>? data = await _service.GetAll();
return View(data);
}
public IActionResult Create()
{
return View();
}
}
}
I am using .NET 6 and Visual Studio version 17.2.5.
What could be the problem? Thanks in advance

Model attribute inconsistent after form submission

I'm still trying to figure out what's happening on the backend here. Working with Spring Boot/Thymeleaf. I have a form template that updates a model attribute object on save. I'm trying to use the updated values on the backend, however it's inconsistent among my functions and I'm not sure why.
Thymeleaf template
<div layout:fragment="content" class="container">
<form action="#" th:action="#{/utility/exportbadges}" th:object="${badgeExport}" method="post">
<div class="form-group col-md-6">
<label class="col-form-label-sm">Badge type</label>
<select th:field="*{type}" class="form-control">
<option th:each="badgeType : ${T(org.myorg.myproject.model.badge.BadgeType).values()}"
th:value="${badgeType}"
th:text="${badgeType}">
</option>
</select>
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Use background?</label>
<input type="checkbox" th:field="*{background}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Mark preprinted?</label>
<input type="checkbox" th:field="*{preprinted}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Save to path (/tmp default):</label>
<input type="text" th:field="*{saveDir}" class="form-control" placeholder="/tmp">
</div>
<div class="form-group col-md-12 mt-2">
<div class="col-sm-10">
<input class="btn btn-primary" id="save" type="submit" value="Export" />
<input class="btn btn-secondary" type="reset" value="Reset" />
</div>
</div>
</form>
</div>
#RequestMapping(value = "/utility/exportbadges")
public String exportBadges(Model model) {
final BadgeExport badgeExport = new BadgeExport();
model.addAttribute("badgeExport", badgeExport);
return "utility/exportbadges";
}
POST method. The object is correct in this function. Any field that's edited in the form above reflects in this function. However, on redirect, the object is as if it only has default instantiation/has been unedited.
#RequestMapping(value = "/utility/exportbadges", method = RequestMethod.POST)
public String exportBadgeFlow(Model model,
#ModelAttribute("badgeExport") final BadgeExport badgeExport) {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir pre export: {}", badgeExport.getSaveDir());
switch(badgeExport.getType()) {
case "Attendee":
log.error("Attendee export not yet implemented");
break;
case "Vip":
return "redirect:exportbadges/vip-badges.pdf";
case "Specialty":
return "redirect:exportbadges/specialty-badges.pdf";
case "Staff":
return "redirect:exportbadges/staff-badges.pdf";
case "Guest":
return "redirect:exportbadges/guest-badges.pdf";
}
return "redirect:exportbadges";
}
Redirect function. Badge type will be null and saveDir will be /tmp as default instead of updated value in form.
#RequestMapping(value = "/utility/exportbadges/vip-badges.pdf")
public ResponseEntity<String> getAllVipBadgePdf(#ModelAttribute("badgeExport") final BadgeExport badgeExport) throws IOException {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir during export: {}", badgeExport.getSaveDir());
}

Upload file with Boostrap Modal on Asp.net core 2.1

I want to upload a file and send to email. But I don't see how to do this with Bootsrap Modal.
If you want any other information, tell me.
I would like to send the attached file by email then also integrate it in my database and be able to download it.
/[...]/ ==> Code that I didn't add, not useful.
Edit : Otherwise how to do with Ajax ?
My View :
<form name="contact" method="post" asp-action="Validation">
#if (ViewBag.Alert != null && ViewBag.Alert != "")
{
<div class="alert role="alert">
#ViewBag.Alert
</div>
}
<div class="details">
<h3 class="title">Demande</h3>
<label for="card">Type *</label>
<select required onchange="contact()" class=" form-control" disabled="true" name="type" value="#ViewBag.Form.Type">
<option value="1">Choose 1</option>
<option value="2">Choose 2</option>
</select>
<label for="card">Origine *</label>
<select required class="form-control" name="origine" value="#ViewBag.Form.Origine">
<option value="1">Origine 1</option>
<option value="2">Origine 2</option>
<option value="3">Origine 3</option>
</select>
/*[...]*/
<input type="hidden" name="Id" value="#ViewBag.Form.Id" />
<input type="hidden" name="Price" value="#ViewBag.Form.Price" />
/*[...]*/
<textarea class="form-control" name="Response" placeholder="Response..."></textarea>
<button required class="btn" onclick="modal_response()" data-whatever="getbootstrap" data-toggle="modal" data-target="#modal_contact" type="button">Response</button>
<label for="card" class="right">Response send</label><br />
<button required class="btn_second" onclick="modal_save()" data-whatever="getbootstrap" data-toggle="modal" data-target="#modal_contact_save" type="button">Save</button>
<label for="card-holder" class="right">Save Ok!</label>
/*[...]*/
<div class="form-row">
<button class="btn-primary" onclick="form_confirmation()" type="submit">Save All</button>
<button class="btn-secondary" type="reset" onclick="location.href = '#Url.Action("List", "Control", new { id = ViewBag.Id })';">Close</button>
</div>
</div>
</form>
/* When I click on "Response" a new window open */
<div class="modal fade" id="modal_contact" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<h5 class="modal-title" id="modal_label">Send email to : #ViewBag.Form.Name</h5>
<button type="button" class="close" data-dismiss="modal"></button>
</div>
<div class="modal-body">
<form id="modal_contact_form" enctype = "multipart/form-data" method="post" action="#Url.Action("Modal_contact", "Control")">
<div class="form-group">
<input type="file" name="file" accept="application/pdf" /><br /><br />
<textarea class="form-control" name="Description" required placeholder="Content">#ViewBag.Response</textarea>
</div>
<input type="hidden" name="Id" value="ID" hidden />
<input type="hidden" name="Price" value="#ViewBag.Form.Price" hidden />
<input type="hidden" name="Type" value="#ViewBag.Form.Type" hidden />
/*[...]*/
<input type="submit" hidden />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" data-dismiss="modal" onclick="$('#modal_contact_form').submit();" class="btn-primary">Send Email</button>
</div>
</div>
My Controller :
public class MyController : BaseEntity
{
[Required]
public string Id { get; set; }
public string Price { get; set; }
public string Type { get; set; }
/*[...]*/
/* For File I don't know if it's good?? */
public IformFile File { get; set; }
}
My Model :
public ActionResult Modal_contact(MyController model)
{
/* How to retrieve file ?? */
bool ok = false;
OtherController OC = new OtherController();
/*[...]*/
if (ModelState.IsValid)
{
OC = othercontrollerRepository.Find(model.Id);
OC.Email = this.Session_get("Email");
OC.Description = "";
model.Email = this.Session_get("Email");
model.Status = "1";
model.View = "response";
/*[...]*/
if (mycontrollerRepository.Add(model) && othercontrollerRepository.Update(OC))
{
/* How to send file to email and save file to folder in my project to add in my database ? */
MailManager mail = new MailManager();
Modele modele = new Modele();
modele= modeleRepository.Find("response");
ok = mail.send(modele.Objet, model.Description, OC.Email);
}
return Json(new { Json_result = ok, Redirect = "" });
}
return Json(new { Json_result = false, Redirect = "" });
}
I found my error :
Form before <div>
I tried your code and reproduced your issue. I noticed that you named the IFormFile object as File.
public IFormFile File { get; set; }
But input file you are getting is named file.
<input type="file" name="file" accept="application/pdf"/><br /><br />
Asp.net core model binding will bind the property according to the input name. This is the reason why you couldn't get the IFormFile value in controller.
To solve this issue, you should change the name of the input to File so that they could match each other.
Like below:
<input type="file" name="File" accept="application/pdf"/><br /><br />
Result:

Vue.js Asp.NET core Form validation

I am currently learning vuejs with asp .net core right now.
I am doing some form validation and adding some error messages.
The error messages are from the Server side here is my sample code:
[HttpPost]
public async Task<IActionResult> AddUser([FromBody] UserModel user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (_context.Users.Any(u => u.UserName == user.UserName))
{
ModelState.AddModelError("UserName", "Username is already in used");
return BadRequest(ModelState);
}
try
{
var userDto = new User
{
FirstName = user.FirstName,
LastName = user.LastName,
Password = user.Password,
UserName = user.UserName
};
_context.Users.Add(userDto);
await _context.SaveChangesAsync();
}
catch(Exception e)
{
ModelState.AddModelError("Saving Error", string.Format("Error in saving user. \nDetails:\n {0}", e.Message));
return BadRequest(ModelState);
}
return Ok();
}
And in the view:
<form v-on:submit.prevent="SaveUser()">
<div class="form-group">
<label for="userName">User Name</label>
<input class="form-control" type="text" id="userName" placeholder="Username" v-model="userName" required :disabled="isEditMode" />
</div>
<div class="form-group">
<label for="userName">First Name</label>
<input class="form-control" type="text" id="firstName" placeholder="First Name" v-model="firstName" required />
</div>
<div class="form-group">
<label for="userName">Last Name</label>
<input class="form-control" type="text" id="lastName" placeholder="Lastname" v-model="lastName" required />
</div>
<div v-if="!isEditMode">
<div class="form-group">
<label for="userName">Password</label>
<input class="form-control" type="password" id="password" placeholder="Password" v-model="password" required />
</div>
</div>
<!--TODO: Distribute to each control-->
<div v-if="hasError">
<ul v-for="error in errors">
<li style="color: red;" v-for="detail in error">{{detail}}</li>
</ul>
</div>
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" #click="backToList()" class="btn btn-danger">Cancel</button>
</form>
Basically I am doing the validations from the server-side.
Currently the error messages are displayed below the controls
And I need to distribute all the error message inline with the inputs.
Can you help me with this?
Thanks in advance.

ApplicationDbContext.Update() doesn't update but saves it as a new record

I am playing in the new APS.NET 5 RC1 environment but the default edit action creates a new entity of the object. I am searched the whole day finding where it goes wrong but I can't find out why it goes wrong.
Controller:
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using SSTv5.Models;
using SSTv5.Models.Organisations;
using SSTv5.Models.Views;
using System.Collections.Generic;
using SSTv5.Models.Global;
namespace SSTv5.Controllers
{
public class OrganisationTypesController : Controller
{
private ApplicationDbContext _context;
private List<Breadcrumb> _bcList = new List<Breadcrumb>();
public OrganisationTypesController(ApplicationDbContext context)
{
_context = context;
}
#region Edit
// GET: OrganisationTypes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
_bcList.Add(new Breadcrumb("OrganisationTypes", true, "Index", "Index"));
_bcList.Add(new Breadcrumb("Edit", false));
ViewBag.BcList = _bcList;
if (id == null)
{
return HttpNotFound();
}
OrganisationType organisationType = await _context.OrganisationType.SingleAsync(m => m.OrganisationTypeId == id);
if (organisationType == null)
{
return HttpNotFound();
}
return View(organisationType);
}
// POST: OrganisationTypes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(OrganisationType organisationType)
{
if (ModelState.IsValid)
{
_context.Update(organisationType);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(organisationType);
}
#endregion
}
}
Form:
#model SSTv5.Models.Organisations.OrganisationType
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<form asp-action="Edit">
<div class="form-horizontal">
<h4>OrganisationType</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrganisationTypeName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="OrganisationTypeName" class="form-control" />
<span asp-validation-for="OrganisationTypeName" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="ClassIcon" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ClassIcon" id="classIcon" />
<span asp-validation-for="ClassIcon" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Edit" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
For anyone else who has this problem the answer is quite simple.
The form doesn't send the ID of the object with it. The only thing you need to do is put the id in a hidden field in the form. Then it will work fine.

Resources