How To Pass Submit Button Value To Controller Action Parameter? - c#

I am trying to save data and edit that data using the button with Id btnSaveAnContinue. Now, whenever I click on Save And Continue button to save data, the command parameter in post method i.e gets Saveandcontinue which is defined in the button as per required.
But whenever, I try to edit the data and save it by clicking on same button, the command parameter in AddEdit POST method does not get Saveandcontinue, it is null.
The View:
<form asp-controller="Doctor" asp-action="AddEdit" method="post" class="form-horizontal" id="DoctorAddEdit" role="form">
#Html.HiddenFor(c => c.DoctorId)
<div class="m-b-md heading-tp-cls">
<h3 class="m-b-none pull-left">Doctor Information <small id="currentUsersInCase"></small></h3>
<div class="doc-buttons pull-right relative">
<button type="submit" class="btn btn-s-md btn-success saveButton" id="btnSave"><i class="fa fa-save fa-fw"></i>Save And Close</button>
<button type="submit" name="command" value="Saveandcontinue" id="btnSaveAnContinue" class="btn btn-s-md btn-success saveButton "><i class="fa fa-save fa-fw"></i>Save And Continue</button>
</div>
<div class="clearfix"></div>
</div>
<section class="panel panel-default tp-section-cls no-left-right-borders" style="padding-top: 10px;">
<div class="row m-l-none m-r-none bg-light lter">
<section>
<div class="col-lg-2 col-md-2 col-sm-6 error-holder-form hideSubject" id="claimanatFirstNameDiv">
<label>First Name<span class="requAstrik">*</span></label>
<input asp-for="FirstName" id="DFirstName" class="form-control subjectHide" placeholder="" type="text">
<span asp-validation-for="FirstName" class="text-danger error"></span>
</div>
<div class="col-lg-2 col-md-2 col-sm-6 hideSubject" id="claimanatMiddleInitialDiv">
<label>Middle Name</label>
<input asp-for="MiddleInitial" id="DMidName" class="form-control subjectHide" placeholder="" type="text">
</div>
</section>
</div>
</section>
</form>
GET method for AddEdit:
public IActionResult AddEdit(int id = 0, bool flag = false)
{
var getDoctorById = _doctorService.GetDoctorInfoById(id);
return View(getDoctorById);
}
POST method for AddEdit:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddEdit(DoctorInfoModel doctorInfo, string command)
{
bool isAjaxCall = HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
if (isAjaxCall)
{
return Content("Saved");
}
if (ModelState.IsValid)
{
var result = 0;
int userId = User.GetUserId();
doctorInfo.CreatedBy = userId;
var saveAndGetUserId = 0;
if (doctorInfo.DoctorId == 0)
{
saveAndGetUserId = _doctorService.SaveUserInfo(doctorInfo);
var user = new ApplicationUser { UserName = doctorInfo.UserName, Email = doctorInfo.DocEmail, UserId = saveAndGetUserId };
var getResult = await _userManager.CreateAsync(user, doctorInfo.Password);
_doctorService.SaveUserRole(user.Id);
}
else
{
var getUserId = _doctorService.GetUser(doctorInfo);
var user = _userManager.Users.FirstOrDefault(c => c.UserId == getUserId);
user.UserName = doctorInfo.UserName;
user.Email = doctorInfo.DocEmail;
if (doctorInfo.Password != null && !"Password#123".Equals(doctorInfo.Password))
{
user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, doctorInfo.Password);
}
try
{
var result1 = await _userManager.UpdateAsync(user);
}
catch (Exception ex)
{
throw;
}
}
var getSaveResult = _doctorService.SaveDoctor(doctorInfo, saveAndGetUserId);
if (getSaveResult.Id > 0)
{
Success(getSaveResult.MessageBody);
}
else
{
Warning(getSaveResult.MessageBody);
}
if (command == "Saveandcontinue")
{
return RedirectToAction(nameof(DoctorController.AddEdit), new { id = getSaveResult.Id, flag = true });
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Doctor");
}
}
Warning("Failed to save Doctor, try again later.");
return View("AddEdit", doctorInfo);
}

Related

Passing image from modal to controller

I have the following application, where I have to upload an image directly from modal to the page.
Note that:
The image is already uploaded by the admin to this modal.
The images are saved in "static" file in "wwwroot" folder. So, No database is required for this step.
All what I need is when I click in the image in the modal, it should be uploaded to the view. So, I can save it later in the database.
Here is Image Bank Controller
public IActionResult Index()
{
var webRoot = _hostingEnvironment.WebRootPath;
var appData = System.IO.Path.Combine(webRoot, "static");
var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
var model = new ImageBankViewModel()
{
ImagesListUrls = files.Select(i=>Path.GetFileName(i))
};
return View(model);
}
[HttpPost]
public IActionResult Upload(ImageBankViewModel model)
{
if (ModelState.IsValid)
{
if (model.Image != null)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var extension = Path.GetExtension(model.Image.FileName);
var newFileName = model.Type + "-" + DateTime.Now.Ticks;
using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
{
model.Image.CopyTo(filesStream);
}
return RedirectToAction("Index");
}
}
ImageBankViewModel modelVM = new ImageBankViewModel()
{
Image = model.Image,
ImagesListUrls = model.ImagesListUrls,
Type = model.Type
};
return RedirectToAction("Index",modelVM);//Unsuccessful Upload , fix invalid model
}
public IActionResult CreateStory()
{
return View();
}
public ActionResult GetImagesPartial()
{
var webRoot = _hostingEnvironment.WebRootPath;
var appData = System.IO.Path.Combine(webRoot, "static");
var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
var model = new ImageBankViewModel()
{
ImagesListUrls = files.Select(i => Path.GetFileName(i))
};
return PartialView("_ImagesBankModal",model);
}
public void ImageDelete(string image)
{
}
public void SelectImage(string image)
{
// Here I want to get the selected image from the modal
}
}
}
Create Story View
#{
ViewData["Title"] = "CreateStory";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>CreateStory</h1>
<div class="row">
<div class="col-md-1">
<label>Pic1</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" />
</div>
<div class="col-md-3">
<a class="btn btn-outline-dark" asp-area="" asp-controller="Bank" asp-action="GetImagesPartial" data-toggle="modal" data-target="#myModal" id="sel">Select from image bank</a>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="partial"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
<label>Pic2</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" />
</div>
<div class="col-md-3">
<button class="btn btn-outline-dark">Select from image bank</button>
</div>
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$('#sel').click(function () {
var route = '#Url.Action("GetImagesPartial", "Bank")';
$('#partial').load(route);
});
});
</script>
}
Modal Partial View
#model TestApplication.Models.ViewModels.ImageBankViewModel
<div class="modal-header">
<h2 class="modal-title">Choose</h2>
</div>
<div class="modal-body">
#if (Model.ImagesListUrls.Any())
{
<table>
#foreach (var image in Model.ImagesListUrls)
{
<tr>
<td>
<a asp-area="" asp-controller="Bank" asp-action="SelectImage" asp-route-image="#image" class="btn btn-light position-absolute" style="right:0">Select</a>
<img src="~/static/#image" class="img-thumbnail" />
</td>
</tr>
}
</table>
}
else
{
<h5>no images exists...</h5>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
</div>
You can store the relative path of the selected picture in an input and pass them to the action.
The following is an example, you can refer to it.
Index
<form asp-action="Upload" asp-controller="ImageBank" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-1">
<label>Pic1</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" name="model.Image"/>
<ul class="selectedpic">
</ul>
</div>
<div class="col-md-3">
<a class="btn btn-outline-dark sel">Select from image bank</a>
</div>
<div class="col-md-8 addedimg">
</div>
</div>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="partial"></div>
</div>
</div>
</div>
<button type="submit">submit</button>
</form>
#section Scripts{
<script type="text/javascript">
var currentsel="";
$('body').on("click",".sel",function () {
localStorage.setItem("currentsel",$(this).attr("class"));
var route = '#Url.Action("GetImagesPartial", "ImageBank")';
$("#myModal").modal("show");
$('#partial').load(route);
});
$('body').on("click",".selectbtn",function () {
var currenttd=$(this).closest("td");
console.log(currenttd.find("img").attr("src"))
var classarry=localStorage.getItem("currentsel").split(" ");
var currentsel="."+classarry[classarry.length-1];
var currentaddedimg=$(currentsel).closest(".row").find(".addedimg");
var addsrc=currenttd.find("img").attr("src");
if(checkisexsist(currentaddedimg,addsrc)){
$(currentsel).closest(".row").find(".selectedpic").append("<li>"+addsrc+"</li>");
$(currentsel).closest(".row").find(".addedimg").append("<input hidden name='selimages' value='"+addsrc+"'/>");
$("#myModal").modal("hide");
$('#myModal').on('hidden.bs.modal', function (e) {
localStorage.removeItem("currentsel");
});
}else{
alert("has selected");
}
});
function checkisexsist(currentaddedimg,addsrc){
var flag=true;
$.each(currentaddedimg.find("input[name='selimages']"), function( index, value ) {
if($(value).val()==addsrc){
flag=false;
}
});
return flag;
}
</script>
}
Controller
[HttpPost]
public IActionResult Upload(ImageBankViewModel model,List<string> selimages)
{
if (ModelState.IsValid)
{
if (model.Image != null)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path =Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var extension = Path.GetExtension(model.Image.FileName);
var newFileName = model.Type + "-" + DateTime.Now.Ticks;
using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
{
model.Image.CopyTo(filesStream);
}
}
if(selimages!=null& selimages.Count != 0)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
selimages.ForEach(m =>
{
var newFileName = Guid.NewGuid().ToString();
var extension = "." + m.Split(".")[m.Split(".").Length - 1];
var oldpath =webRootPath+m.Replace("/", "\\"); var newpath = Path.Combine(path, newFileName + extension);
System.IO.File.Copy(oldpath,newpath);
});
}
return RedirectToAction("Index");
}
ImageBankViewModel modelVM = new ImageBankViewModel()
{
Image = model.Image,
ImagesListUrls = model.ImagesListUrls,
Type = model.Type
};
return RedirectToAction("Index", modelVM);//Unsuccessful Upload , fix invalid model
}
_ImagesBankModal(Only give the modified place)
<a class="btn btn-light position-absolute selectbtn">Select</a>
Result

Check If Email alredy exist while user is register ASP.NET CORE MVC Identity

I am trying to check if User enter existing email addres and display ErrorMessage
So far here is what I do
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
ApplicationUser user = new()
{
UserName = Input.Email,
Email = Input.Email,
ClientId = Input.ClientId,
StreetAddress = Input.StreetAddress,
City = Input.City,
PostalCode = Input.PostalCode,
Name = Input.Name,
PhoneNumber = Input.PhoneNumber,
Role = Input.Role,
Aktivan = false
};
var emailExist = _db.ApplicationUsers.Any(x => x.Email == Input.Email);
if (emailExist)
{
ModelState.AddModelError("Email", "Korisnicki email vec postoji!");
return Page();
}
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
if (!await _roleManager.RoleExistsAsync(SD.Role_Admin))
{
await _roleManager.CreateAsync(new IdentityRole<int>(SD.Role_Admin));
}
if (!await _roleManager.RoleExistsAsync(SD.Role_Manager))
{
await _roleManager.CreateAsync(new IdentityRole<int>(SD.Role_Manager));
}
if (user.Role == null)
{
await _userManager.AddToRoleAsync(user, SD.Role_Manager);
}
else
{
await _userManager.AddToRoleAsync(user, user.Role);
}
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
//var callbackUrl = Url.Page(
// "/Account/ConfirmEmail",
// pageHandler: null,
// values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
// protocol: Request.Scheme);
//await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
// $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl });
}
else
{
if (user.Role == null)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
else
{
// admin registering new user
return RedirectToAction("Index", "User", new { Area = "Admin" });
}
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
So I check If email alredy exist
var emailExist = _db.ApplicationUsers.Any(x => x.Email == Input.Email);
if (emailExist)
{
ModelState.AddModelError("Email", "Korisnicki email vec postoji!");
return Page();
}
And I add also in my Register View
<body class="hold-transition register-page">
<div class="register-box">
<div class="register-logo">
<b>VmS</b>Group
</div>
<div class="card">
<div class="card-body register-card-body">
<form asp-route-returnUrl="#Model.ReturnUrl" method="post">
<h4>Registracija Korisnika</h4>
<hr />
<div class="form-group">
<label>Ime i Prezime</label>
<input asp-for="Input.Name" class="form-control" />
<span asp-validation-for="Input.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label>Adresa</label>
<input asp-for="Input.StreetAddress" class="form-control" />
<span asp-validation-for="Input.StreetAddress" class="text-danger"></span>
</div>
<div class="form-group">
<label>Grad</label>
<input asp-for="Input.City" class="form-control" />
<span asp-validation-for="Input.City" class="text-danger"></span>
</div>
<div class="form-group">
<label>Postanski broj</label>
<input asp-for="Input.PostalCode" class="form-control" />
<span asp-validation-for="Input.PostalCode" class="text-danger"></span>
</div>
<div class="form-group">
<label>Broj telefona</label>
<input asp-for="Input.PhoneNumber" class="form-control" />
<span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label>Email adresa</label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label>Lozinka</label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label>Potvrdi lozinku</label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
#if (User.IsInRole(SD.Role_Admin))
{
<div class="form-group">
<label asp-for="Input.Role">Korisnicka Uloga</label>
#Html.DropDownListFor(m => m.Input.Role, Model.Input.RoleList,
"-Izaberite korisnicku ulogu-", new { #class = "form-control" })
</div>
<div class="form-group">
<label asp-for="Input.ClientId">Klijent</label>
#Html.DropDownListFor(m => m.Input.ClientId, Model.Input.ClientList,
"-Izaberite klijenta-", new { #class = "form-control" })
</div>
<a asp-area="Admin" asp-controller="User" asp-action="Index" class="btn btn-warning" style="width:auto">Nazad</a>
}
<button type="submit" class="btn btn-primary">Registruj se</button>
#*<a asp-area="Admin" asp-controller="User" asp-action="Index" class="btn btn-warning" style="width:auto">Back to User</a>*#
</form>
#if (User.IsInRole(SD.Role_Manager))
{
<a asp-area="Identity" asp-page="/Account/Login" class="text-center">Ukoliko vec imate aktivan korisnicki nalog</a>
}
</div>
</div>
</div>
<script src="~/plugins/jquery/jquery.min.js"></script>
<script src="~/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="~/dist/js/adminlte.min.js"></script>
</body>
But here is problem that I didn't get any erro message in Register page when I enter existing email address. What is wrong here ? Where did I made mistake ?

Blazor List Refresh After Update

This post is entirely updated to put all code in one class and to try to make it as straight-forward as possible.
The project works perfectly EXCEPT for one thing: When a student record is updated, the database is updated, but the visible list does not update.
The only way I've been able to see the changes is when I refresh the entire page (see NavigationManager line at bottom of code).
Can you please help me understand what I'm not doing right here.
#page "/Students2";
#using ParentChild.Models;
#inject IJSRuntime JS; // Used for Confirmation Dialog & Alert Box
#inject NavigationManager NavigationManager // Used to Refresh Entire Page
<h3>Students 2</h3>
#if (byStudents == null)
{
<p><em>Loading...</em></p>
}
else if (!byStudents.Any())
{
<p><em>No students in database. Please add some.</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>First</th>
<th>Last</th>
<th>Street</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Cell</th>
<th>Home</th>
<th>Email</th>
<th>Note</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var byStudent in byStudents)
{
<tr>
<td>#byStudent.SFirst</td>
<td>#byStudent.SLast</td>
<td>#byStudent.SStreet</td>
<td>#byStudent.SCity</td>
<td>#byStudent.SState</td>
<td>#byStudent.SZip</td>
<td>#byStudent.SCell</td>
<td>#byStudent.SHome</td>
<td>#byStudent.SEmail</td>
<td>#byStudent.SNote</td>
<td>
<input type="button" class="btn btn-primary" #onclick="#(() => OpenEditStudent(#byStudent.SId))" value="Edit" />
<nbsp></nbsp>
<input type="button" class="btn btn-danger" #onclick="#(async () => await DeleteStudentAction(#byStudent.SId))" value="Delete" />
</td>
</tr>
}
</tbody>
</table>
}
<button class="btn btn-primary" #onclick="() => OpenAddStudent()">Add New Student</button>
#if (showBackdrop)
{
<div class="modal-backdrop fade show"></div>
}
<!-- Define Modal Pop-UP in this Page -->
<div class="modal #modalClass" tabindex="-1" role="dialog" style="display:#modalDisplay; overflow-y: auto;">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<!-- Pop-Up Title Section -->
#{
var txt = "";
if ((SId == null) | (SId == ""))
{
txt = "Add Student";
#txt;
}
else
{
txt = "Edit Student";
#txt;
}
}
</h5>
<!-- Pop-Up Close Button at Top -->
<button type="button" class="close" data-dismiss="modal" aria-label="Close" #onclick="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- Pop-Up Body Section -->
<div class="form-group row">
<input id="SId" #bind="SId" type="hidden" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SFirst" class="col-sm-8 col-form-label">First Name:</label>
<input id="SFirst" #bind="SFirst" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SLast" class="col-sm-8 col-form-label">Last Name:</label>
<input id="SLast" #bind="SLast" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SStreet" class="col-sm-8 col-form-label">Street:</label>
<input id="#SStreet" #bind="SStreet" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SCity" class="col-sm-8 col-form-label">City:</label>
<input id="#SCity" #bind="SCity" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SState" class="col-sm-8 col-form-label">State:</label>
<input id="#SState" #bind="SState" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SZip" class="col-sm-8 col-form-label">Zip:</label>
<input id="#SZip" #bind="SZip" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SCell" class="col-sm-8 col-form-label">Cell #:</label>
<input id="#SCell" #bind="SCell" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SHome" class="col-sm-8 col-form-label">Home #:</label>
<input id="#SHome" #bind="SHome" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SEmail" class="col-sm-8 col-form-label">Email:</label>
<input id="#SEmail" #bind="SEmail" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SNote" class="col-sm-8 col-form-label">Note:</label>
<input id="#SNote" #bind="SNote" class="col-sm-4 form-control" />
</div>
</div>
<div class="modal-footer">
<!-- Pop-Up Body Section -->
#{
if ((SId == null) | (SId == ""))
{
<button type="button" class="btn btn-primary" #onclick="async () => await AddStudentAction()">Add</button>
}
else
{
<button type="button" class="btn btn-primary" #onclick="async () => await UpdateStudentAction(this.SId)">Update</button>
}
}
<button type="button" class="btn btn-secondary" data-dismiss="modal" #onclick="() => this.Close()">Close</button>
</div>
</div>
</div>
</div>
#code {
//-------------------------------------------------------------------------
// Modal Control Variables and Code
//-------------------------------------------------------------------------
private string modalDisplay = "none;";
private string modalClass = "";
private bool showBackdrop = false;
//--- Open Modal...
public void Open()
{
modalDisplay = "block;";
modalClass = "show";
showBackdrop = true;
}
//--- Close Modal...
public void Close()
{
modalDisplay = "none";
modalClass = "";
showBackdrop = false;
}
//-------------------------------------------------------------------------
// Student List from Database
//-------------------------------------------------------------------------
DB_136837_byogaContext db = new DB_136837_byogaContext();
private List<ByStudents> byStudents;
//--- Build Student List on Page Initialization...
protected override void OnInitialized()
{
byStudents = db.ByStudents.ToList();
}
//-------------------------------------------------------------------------
// Modal Parameters
//-------------------------------------------------------------------------
private Modal modal { get; set; }
[Parameter]
public string SId { get; set; } = "";
[Parameter]
public string SFirst { get; set; } = "";
[Parameter]
public string SLast { get; set; } = "";
[Parameter]
public string SStreet { get; set; } = "";
[Parameter]
public string SCity { get; set; } = "";
[Parameter]
public string SState { get; set; } = "";
[Parameter]
public string SZip { get; set; } = "";
[Parameter]
public string SCell { get; set; } = "";
[Parameter]
public string SHome { get; set; } = "";
[Parameter]
public string SEmail { get; set; } = "";
[Parameter]
public string SNote { get; set; } = "";
//-------------------------------------------------------------------------
// Open Modal to Add Student
//-------------------------------------------------------------------------
protected void OpenAddStudent()
{
//-- Clear Any Info Set in Previous Edit Requests...
SId = "";
SFirst = "";
SLast = "";
SStreet = "";
SCity = "";
SState = "";
SZip = "";
SCell = "";
SHome = "";
SEmail = "";
SNote = "";
//--- Open Modal Popup...
this.Open();
}
//-------------------------------------------------------------------------
// Open Modal to Edit Student
//-------------------------------------------------------------------------
protected void OpenEditStudent(int myID)
{
//--- Build & Run SQL Select Statement...
using (var myContext = new DB_136837_byogaContext())
{
//--- Grab Info for Selected Student...
var myQuery = (from s in myContext.ByStudents where s.SId == myID select s).Single();
//--- Set Fields on Popup Form...
this.SId = myQuery.SId.ToString();
this.SFirst = myQuery.SFirst;
this.SLast = myQuery.SLast;
this.SStreet = myQuery.SStreet;
this.SCity = myQuery.SCity;
this.SState = myQuery.SState;
this.SZip = myQuery.SZip;
this.SCell = myQuery.SCell;
this.SHome = myQuery.SHome;
this.SEmail = myQuery.SEmail;
this.SNote = myQuery.SNote;
}
//--- Open Modal Form...
this.Open();
}
//-------------------------------------------------------------------------
// Delete Selected Student from Database with Confirmation Dialog
//-------------------------------------------------------------------------
protected async Task DeleteStudentAction(int myID)
{
bool isConfirmed = await JS.InvokeAsync<bool>("confirm", $"Do you sure you want to permanently delete whis record?");
if (isConfirmed)
{
//--- Build & Run SQL Delete Statement...
using (var myContext = new DB_136837_byogaContext())
{
var myQuery = (from d in myContext.ByStudents where d.SId == myID select d).Single();
myContext.ByStudents.Remove(myQuery);
myContext.SaveChanges();
}
//--- Delete Complete Dialog...
await JS.InvokeVoidAsync("alert", "Record Deleted");
//--- Refresh Page...
await InvokeAsync(() =>
{
StateHasChanged();
this.OnInitialized();
});
}
}
//-------------------------------------------------------------------------
// Add Student to Database
//-------------------------------------------------------------------------
protected async Task AddStudentAction()
{
//--- Define the New Student...
var newStudent = new ByStudents();
newStudent.SFirst = SFirst;
newStudent.SLast = SLast;
newStudent.SStreet = SStreet;
newStudent.SCity = SCity;
newStudent.SState = SState;
newStudent.SZip = SZip;
newStudent.SCell = SCell;
newStudent.SHome = SHome;
newStudent.SEmail = SEmail;
newStudent.SNote = SNote;
//--- Add New Student to Database...
using (var myContext = new DB_136837_byogaContext())
{
myContext.ByStudents.Add(newStudent);
myContext.SaveChanges();
}
//--- Close the Popup...
this.Close();
//--- Refresh Page...
await InvokeAsync(() =>
{
StateHasChanged();
this.OnInitialized();
});
}
//-------------------------------------------------------------------------
// Update Student in Database
//-------------------------------------------------------------------------
protected async Task UpdateStudentAction(string myID)
{
//--- Build & Run SQL Select Statement...
using (var myContext = new DB_136837_byogaContext())
{
//--- Update Info for Selected Student...
var myQuery = (from d in myContext.ByStudents where d.SId == Convert.ToInt32(myID) select d).Single();
myQuery.SFirst = this.SFirst;
myQuery.SLast = this.SLast;
myQuery.SStreet = this.SStreet;
myQuery.SCity = this.SCity;
myQuery.SState = this.SState;
myQuery.SZip = this.SZip;
myQuery.SCell = this.SCell;
myQuery.SHome = this.SHome;
myQuery.SEmail = this.SEmail;
myQuery.SNote = this.SNote;
myContext.ByStudents.Update(myQuery);
myContext.SaveChanges();
}
//--- Close the Popup...
this.Close();
//--- Refresh Page...
await InvokeAsync(() =>
{
StateHasChanged();
this.OnInitialized();
});
//--- Refresh Page by Reloading...SHOULD NOT HAVE TO DO THIS!
//NavigationManager.NavigateTo("Refresh/Students2");
}
}
Any and all help is appreciated. Thanks!
On your add/update page, after you are done with your operation and you are navigating back to your list, add the 'true' parameter to force a reload of the list page.
NavigationManager.NavigateTo("students", true);
See this link
If I understand correctly, you have a child component modal that handles the crud responsible for data displayed by a parent component.
I believe if you call StateHasChanged() from a child component the state is updated in the child component's scope unless the parent is notified its state should be updated. I would try adding an eventcallback from your child component modal to the parent that triggers a StateHasChanged() on the parent level. You could manually invoke the callback on any child crud methods after the work is done.
Something similar to this: Blazor - Execute a parent component's method when a child component onclick event occurs

How to get the data-id Send to another controller mvc

How to get the data-id sent to another controller in ASP.NET MVC?
The employee submits the form, automatically determines the id and department position, and then sends it to the manager for approval.
The manager clicks approval or reject on this page, and the form is sent to the next person for approval. At this step, the page prompts that id = null cannot be run. What should I do?
But Google background shows that I got this Id, how to send this Id to action?
public PartialViewResult saveStatus(int id, string Status, string AddDate, string Remark)
{
int approvalId;
if (id == 0 && Session["AppId"] == null)
{
var staff = db.Staffs.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
RequestForApproval ap = new RequestForApproval
{
RequestToStaffId = staff.Id,
RequestDate = DateTime.Now,
};
db.RequestForApprovals.Add(ap);
db.SaveChanges();
Session["AppId"] = ap.ReimbursementID;
approvalId = ap.Id;
}
else
{
approvalId = int.Parse(Session["AppId"].ToString());
}
ApprovalStatus temp = new ApprovalStatus
{
Id = approvalId,
Remark = Remark,
AddDate = DateTime.Now
};
db.ApprovalStatuses.Add(temp);
db.SaveChanges();
var df = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
return PartialView(df);
}
public JsonResult CreateStatus()
{
List<ApprovalStatus> mv = new List<ApprovalStatus>();
if(Session["AppId"] == null)
{
ViewBag.Ae = 0;
}
else
{
ViewBag.Ae = Session["AppId"];
int approvalId = int.Parse(Session["AppId"].ToString());
mv = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
}
return Json(mv);
}
public ActionResult AddRequestForApproval()
{
// var staffUser = db.StaffPositions.Where(a => a.Staff.UserName == System.Web.HttpContext.Current.User.Identity.GetUserId());
var rmid = Session["RmId"].ToString();
if (string.IsNullOrEmpty(rmid))
{
return RedirectToAction("Index");
}
int reimbursementId = int.Parse(rmid);
Session["RmId"] = null;
var Res = db.Reimbursements.Find(reimbursementId);
var managerId = GetByStaffId(Res.StaffId,reimbursementId);
RequestForApproval temp = new RequestForApproval();
temp.ReimbursementID = reimbursementId;
temp.RequestDate = DateTime.Now;
temp.RequestToStaffId = managerId;
db.RequestForApprovals.Add(temp);
db.SaveChanges();
return RedirectToAction("Index");
}
View:
#model Reimbursements.Models.RequesViewModel
#{
ViewBag.Title = "Index";
var add = Session["AppId"];
}
<h2>Index</h2>
<table class="table" id="table1">
<tr>
<th></th>
<th>
Staff Fname
</th>
<th>
RequestDate
</th>
<th></th>
</tr>
#foreach (var item in Model.GetReApproval)
{
<tr>
<td>
#item.ReimbursementId
</td>
<td>
#item.StaffName
</td>
<td>
#item.RequestDate
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-id="#item.RequerForApprovalId" data-target="#exampleModal" id="SelectBtn">Select</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="Title">Select and Confirm</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group" >
<input type="hidden" id="Reid" />
#Html.DropDownList("ApprovalStatus", null, new { #class = "btn btn-info",id="enumId" })
#*#Html.DropDownList("Index", ViewBag.DropDownList as SelectList,null, new { #class = "btn btn-info",#id="DropDownList" })*#
</div>
<hr />
<div class="form-group" style="visibility:visible" id="remarktext">
<label for="message-text" class="control-label">Remark:</label>
<textarea class="form-control" id="message-text" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
#*<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Confirme</button>*#
<button data-id="#item.ReimbursementId" class="btn btn-primary" id="Submit" #*onclick="location.href='#Url.Action("AddRequestForApproval","Reimbursements")'"*#>Submit</button>
<button class="btn btn-default" data-dismiss="modal" type="reset" id="Clear">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
</table>
#section Scripts {
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#table1").on('click', '#SelectBtn', function () {
$('#Submit').click('#enumId', function () {
var bid = $(this).attr('data-id');
var status = $("#enumId option:selected").val();
var mess = $('#message-text').val();
var Rmid;
console.log(bid, status, mess);
// var b = $("#NewId");
#*if ($("#NewId").val() == undefined) {
Rmid = 0;
} else {
Rmid = $("#NewId").val();
}
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("saveStatus")',
data: { id: bid, status: status, Remark: mess },
success: function (data) {
console.log(data);
status.val('').url(data);
mess.val('');
}, error: function (data) {
alert("error");
},
})*#
})
})
})
</script>
}
Instead of putting data-id there, you can just put it as value of a hidden filed in your form so that it gets posted when the form submitted:
<input type = "hidden" name="id" value="#item.ReimbursementId" />
If the value may change that you want to send different values when different buttons are clicked, then you can have a hidden input and set its value before submit:
$('#Submit').click('#enumId', function () {
var bid = $(this).data('id');
$('[name="id"]').val(bid);
// rest of your code....
});
Edit: if you are going to post it with ajax, please note that you should get data like:
$(this).data('id');

How to insert json message in modal with asp.net mvc

I'm developing a system in .NET and I need to send a json controller msg to the view and show it in modal.
The user will import a spreadsheet and the spreadsheet will be inserted in the database, at the end of the modal it should appear with the message whether it was sent or not.
Or backend is already working.
 
I need help on the front because when I import, it loads a new page with
["Sent with success"]
(the messages are in portuguese) = ["Enviado com sucesso"]
Follows the controller code.
public JsonResult UploadExcel(HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = "C:/Users/70561/Documents";
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var adapter = new OleDbDataAdapter("SELECT * FROM [Planilha1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Planilha1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var dados = from a in excelFile.Worksheet<RETORNO_CM>(sheetName) select a;
foreach (var a in dados)
{
try
{
if (a.CM_CODIGO != null && a.CM_QM_COMPONENTE_RMA != null && a.CM_NS != null && a.CM_DESCRICAO != null &&
a.CM_DEFEITO != null && a.J_FALHA != null &&
a.CM_TIPO_DEFEITO != null && a.J_PLACA_RETRABALHO != null &&
a.J_PLACA_RESTESTADA != null && a.J_STATUS != null && a.CM_NOME_TESTE != null && a.CM_NOME_DEBUG != null)
{
RETORNO_CM CM = new RETORNO_CM();
CM.CM_CODIGO = a.CM_CODIGO;
CM.CM_QM_COMPONENTE_RMA = a.CM_QM_COMPONENTE_RMA;
CM.CM_NS = a.CM_NS;
CM.CM_DESCRICAO = a.CM_DESCRICAO;
CM.CM_DATA_REPARO = a.CM_DATA_REPARO;
CM.CM_DEFEITO = a.CM_DEFEITO;
CM.J_FALHA = a.J_FALHA;
CM.CM_TIPO_DEFEITO = a.CM_TIPO_DEFEITO;
CM.CM_COMPONENTE = a.CM_COMPONENTE;
CM.J_PLACA_RETRABALHO = a.J_PLACA_RETRABALHO;
CM.J_PLACA_RESTESTADA = a.J_PLACA_RESTESTADA;
CM.J_STATUS = a.J_STATUS;
CM.CM_NOME_TESTE = a.CM_NOME_TESTE;
CM.CM_NOME_DEBUG = a.CM_NOME_DEBUG;
db.RETORNO_CM.Add(CM);
db.SaveChanges();
}
else
{
data.Add("<ul>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
//deleting excel file from folder
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
data.Add("Enviado com sucesso");
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
//alert message for invalid file format
data.Add("Apenas arquivos excel sao suportados");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
if (FileUpload == null) data.Add("Selecione um arquivo");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
my view code
<div class="box">
<div class="box-body">
<hr />
<article class="table-responsive" style="overflow:hidden">
<p class="lead">Teste de importação.</p>
<hr />
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return myFunction()" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enviar" id="btnSubmit" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>
<b>Message:</b><br>
<input class="message-edit-text" type="text" size="20">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</article>
</div>
You should not return JSON, as you are performing a full page postback. Instead, you should return a View.
If you do not want to perform a full page postback, you want to use Ajax since the beginning of the request.
For example,
View
Please make sure button is type="button" to avoid full page postback.
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" id="btnSubmit" class="btn btn-primary">
Enviar
</button>
</div>
</div>
</div>
}
<script>
$(function () {
$('#btnSubmit').click(function() {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '#Url.Action("UploadExcel", "RetornoCM")',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function(result) {
alert(result);
},
error: function(err) {
alert(err.statusText);
}
});
}
});
});
</script>
Action Method
[HttpPost]
public ActionResult UploadExcel()
{
if (Request.Files.Count > 0)
{
try
{
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
// Do somethig with file
}
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Source: File Upload Through JQuery AJAX In ASP.NET MVC

Categories