Image not displaying in view for ASP.NET Core MVC app but dev tools shows it is there - asp.net-core-mvc

I am still fairly new to ASP.NET Core and I am not 100% sure on what I am doing, but I have hobbled together a recipe keeper program, but I am having issues displaying the images.
When I run the program, the view shows that it is getting the image file name and the dev tools shows the correct src code, but the image is still not showing up. I have the code set to show a generic "no image" image when the view can't find the image assigned to the particular recipe but that shouldn't be the case.
I originally had this part working and I'm not sure why it is not anymore. I have tried to retrace my steps from when I noticed the issue, but it has been several days since I completed the image part of this program, so I am not sure where the issue is.
View showing image is there
Page showing generic image
DevTools showing the src
RecipeController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WhatsForDinner.Data;
using WhatsForDinner.Models;
namespace WhatsForDinner.Controllers
{
public class RecipesController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment webHostEnvironment;
public RecipesController(ApplicationDbContext context, IWebHostEnvironment webHostEnvironment)
{
_context = context;
this.webHostEnvironment = webHostEnvironment;
}
// GET: Recipes
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Recipes
.Include(r => r.ApplicationUser)
.Where(a => a.ApplicationUser.Id == HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
return View(await applicationDbContext.ToListAsync());
}
// GET: Recipes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.Recipes == null)
{
return NotFound();
}
var recipe = await _context.Recipes
.Include(r => r.ApplicationUser)
.FirstOrDefaultAsync(m => m.RecipeId == id);
if (recipe == null)
{
return NotFound();
}
return View(recipe);
}
// GET: Recipes/Create
public IActionResult Create()
{
//ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id");
//ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View();
}
// POST: Recipes/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("RecipeId, UploadDateAndTime, RecipeTitle, RecipeDescription, PrepTime, NumOfServings, ServingSize, Ingredients, Directions, Notes, RecipePhoto, ApplicationUserId, RecipePhoto")] Recipe recipe, IFormFile file)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if (file != null)
{
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Images");
uniqueFileName = file.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(fileStream);
}
}
recipe.RecipePhoto = uniqueFileName;
recipe.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
_context.Add(recipe);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
// ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id", recipe.ApplicationUserId);
// ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View(recipe);
}
// GET: Recipes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null || _context.Recipes == null)
{
return NotFound();
}
var recipe = await _context.Recipes.FindAsync(id);
if (recipe == null)
{
return NotFound();
}
// ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id", recipe.ApplicationUserId);
// ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View(recipe);
}
// POST: Recipes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("RecipeId, UploadDateAndTime, RecipeTitle, RecipeDescription, PrepTime, NumOfServings, ServingSize, Ingredients, Directions, Notes, ApplicationUserId")] Recipe recipe)
{
if (id != recipe.RecipeId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
recipe.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
_context.Update(recipe);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!RecipeExists(recipe.RecipeId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
// ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id", recipe.ApplicationUserId);
// ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View(recipe);
}
// GET: Recipes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null || _context.Recipes == null)
{
return NotFound();
}
var recipe = await _context.Recipes
.Include(r => r.ApplicationUser)
.FirstOrDefaultAsync(m => m.RecipeId == id);
if (recipe == null)
{
return NotFound();
}
return View(recipe);
}
// POST: Recipes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
if (_context.Recipes == null)
{
return Problem("Entity set 'ApplicationDbContext.Recipes' is null.");
}
var recipe = await _context.Recipes.FindAsync(id);
if (recipe != null)
{
_context.Recipes.Remove(recipe);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool RecipeExists(int id)
{
return _context.Recipes.Any(e => e.RecipeId == id);
}
}
}
I am not sure why the images are not showing anymore. Any thoughts?

I am not sure why the images are not showing anymore. Any thoughts?
Well, your issue is pretty obvious, as you are using type="image/*" to display image. However, this is not the correct way to do that. I have reproduced your issue thus have a look the solution as well.
Solution:
You should use accept="image/*"> instead of type="image/*". This the reason your image has not displayed. Your full code should be as following:
<td>
<object class="card-img-top" height="50" width="75" data="~/Image/#Html.DisplayFor(modelItem=>item.RecipePhoto)" accept="image/*">
</object>
</td>
Another way:
<td>
<object class="card-img-top" height="50" width="75" data="~/ImageName/Cover/#item.RecipePhoto" accept="image/*">
</object>
</td>
Output:

Related

how to add and delete favorites in asp.net core api

I develop a news application with ASP.net API. I want users to be able to add and deleted their favorites articles. I created a Favorites model like this:
public class Favorites{
public String userId {get; set;}
public UserEntity User {get; set;}
public int articleId {get; set; }
public virtual Article article {get; set;}
}
I initialized it with dotnet fluentapi:
modelBuilder.Entity<Favorites>().HasKey(a => new{ a.articleId, a.userId });
this is how the controller looks like :
public class FavoritesController : ControllerBase
{
private readonly DatabaseContext _context;
public FavoritesController(DatabaseContext context)
{
_context = context;
_context.Database.EnsureCreated();
}
// GET: api/Favorites
[HttpGet(Name = nameof(GetAllFavorites))]
public async Task<ActionResult<IEnumerable<FavoriteDTo>>> GetAllFavorites( [FromQuery] NewRoomQueryParameters queryParameter)
{
IQueryable<Favorites> favs = _context.Favorites;
if (!string.IsNullOrEmpty(queryParameter.sortBy))
{
if (typeof(Favorites).GetProperty(queryParameter.sortBy) != null)
{
favs = favs.OrderByCustom(queryParameter.sortBy, queryParameter.SortOrder);
}
}
if (!string.IsNullOrEmpty(queryParameter.userId))
{
favs = favs.Where(p => p.userId == queryParameter.userId);
}
return await favs.Include(a => a.Article)
.ThenInclude(a => a.Author)
.Include(a => a.Article)
.ThenInclude(a => a.Comments)
.Select(x => favoriteToDTo(x)).ToListAsync();
}
// GET: api/Favorites/5
[HttpGet("{id}")]
public async Task<ActionResult<FavoriteDTo>> GetFavorites(int id)
{
IQueryable<Favorites> favs = _context.Favorites;
var favorites = await favs.Include(x => x.Article).FirstOrDefaultAsync(x => x.articleId == id ) ;
if (favorites == null)
{
return NotFound();
}
return favoriteToDTo(favorites);
}
// POST: api/Favorites
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<FavoriteDTo>> PostFavorites(FavoriteDTo favDTo)
{
var fav = new Favorites
{
articleId = favDTo.articleId,
userId = favDTo.userId
};
_context.Favorites.Add(fav);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (FavoritesExists(fav.articleId))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtAction(nameof(GetFavorites), new { id = fav.articleId }, fav);
}
// DELETE: api/Favorites/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteFavorites(int id)
{
var favorites = await _context.Favorites.FindAsync(id);
if (favorites == null)
{
return NotFound();
}
_context.Favorites.Remove(favorites);
await _context.SaveChangesAsync();
return NoContent();
}
private static FavoriteDTo favoriteToDTo(Favorites favorites) => new FavoriteDTo
{
articleId = favorites.articleId,
Article = favorites.Article,
User = favorites.User,
userId = favorites.userId
};
private bool FavoritesExists(int id)
{
return _context.Favorites.Any(e => e.articleId == id);
}
}
I can add Favorites just fine. But I cannot remove them. Can somebody help me out ? if it is not the good
way to implement this functionality , please I would like to learn how to do it the right way.
It depends on How you want to delete the favorite. If you want to delete the Article from Favorite for a user,
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteFavoritesForUser(int Articleid, string userId)
{
var favorites = await _context.Favorites.FindBy(x=>x.UserId ==userId && x=>x.ArticleId ==Articleid);
if (favorites == null)
{
return NotFound();
}
_context.Favorites.RemoveRange(favorites);
await _context.SaveChangesAsync();
return NoContent();
}
Replace
_context.Favorites.Remove(favorites);
with
_context.Favorites.RemoveRange(favorites);

how to delete functionalitty with client confirmation in asp.net core mvc 6

i have a delete method but i don't know how to delete with client confirmation,
i have a method of delete
public async Task<IActionResult> Delete(int? id, bool? saveChangesError = false)
{
if (id == null)
{
return NotFound();
}
var student = await _context.userAccount
.AsNoTracking()
.SingleOrDefaultAsync(m => m.UserID == id);
if (student == null)
{
return NotFound();
}
if (saveChangesError.GetValueOrDefault())
{
ViewData["ErrorMessage"] =
"Delete failed. Try again, and if the problem persists " +
"see your system administrator.";
}
return View();
}
// POST: Students/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
try
{
UserAccount accToDelete = new UserAccount() { UserID = id };
_context.Entry(accToDelete).State = EntityState.Deleted;
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
how to client confirmation on first click in asp.net core mvc 6.
any new idea or any modification

Complex Custom Validation in Foolproof Validation

I have implemented Complex custom Foolproof validation in my application from this link but sadly its not working.My requirement is simple,I have a input file for uploading an image and there should be a validation if the user chooses to upload file other than specified below
".jpg",".png",".gif",".jpeg"
Code is
[Required(ErrorMessage = "Please upload Photo", AllowEmptyStrings = false)]
[IsValidPhoto(ErrorMessage="Please select files of type .jpg,.png,.gif,.jpeg")]
public HttpPostedFileBase PhotoUrl { get; set; }
public class IsValidPhotoAttribute : ModelAwareValidationAttribute
{
//this is needed to register this attribute with foolproof's validator adapter
static IsValidPhotoAttribute() { Register.Attribute(typeof(IsValidPhotoAttribute)); }
public override bool IsValid(object value, object container)
{
if (value != null)
{
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" };
var file = value as HttpPostedFileBase;
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
return false;
}
}
return true;
}
}
CSHTML is
#Html.TextBoxFor(m => m.PhotoUrl, new { #class = "form-control imgUpload",
#placeholder = "Please upload Photo", #id = "txtPhoto", #type = "file" })
#Html.ValidationMessageFor(m => m.PhotoUrl)
You will not be able to get client side validation unless you also create a script to add the rules. It is not necessary to use foolproof and the following method and scripts will give you both server and client side validation
public class FileAttachmentAttribute : ValidationAttribute, IClientValidatable
{
private List<string> _Extensions { get; set; }
private const string _DefaultErrorMessage = "Only file types with the following extensions are allowed: {0}";
public FileAttachmentAttribute(string fileExtensions)
{
_Extensions = fileExtensions.Split('|').ToList();
ErrorMessage = _DefaultErrorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
HttpPostedFileBase file = value as HttpPostedFileBase;
if (file != null)
{
var isValid = _Extensions.Any(e => file.FileName.EndsWith(e));
if (!isValid)
{
return new ValidationResult(string.Format(ErrorMessageString, string.Join(", ", _Extensions)));
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "fileattachment",
ErrorMessage = string.Format(ErrorMessageString, string.Join(", ", _Extensions))
};
rule.ValidationParameters.Add("extensions", string.Join(",", _Extensions));
yield return rule;
}
}
Scripts
$.validator.unobtrusive.adapters.add('fileattachment', ['extensions'], function (options) {
var params = { fileattachment: options.params.extensions.split(',') };
options.rules['fileattachment'] = params;
if (options.message) {
options.messages['fileattachment'] = options.message;
}
});
$.validator.addMethod("fileattachment", function (value, element, param) {
var extension = getExtension(value);
return $.inArray(extension, param.fileextensions) !== -1;
});
function getExtension(fileName) {
var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
if (extension != undefined) {
return extension[0];
}
return extension;
};
and then use it as
[FileAttachment("jpg|gif|png|jpeg")]
public HttpPostedFileBase PhotoUrl { get; set; }

MVC 3 RAZOR - how to use hidden fields to maintain state of checkboxes between page request?

I am using Hidden fields to maintain the state of my checkboxes between page requests except it doesn't work. So when I click on my webgrid to go to the next 15 records it forgets which checkboxes are checked.
Index view
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#{
ViewBag.Title = "User Manager Dashboard";
}
#Html.ActionLink("Create New User", "CreateUser")
#using (#Html.BeginForm())
{
<div class="webgrid-filter">
#{Html.RenderAction("_WebGridFilter", "UserManager");}
</div>
<div id="webgrid-wrapper">
#Html.Partial("~/Views/Partial/_WebGridUserManager.cshtml", Model)
</div>
<br />
}
<script type="text/javascript">
$(document).ready(function () {
// Disable checkboxs where a user is not active.
$(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");
// Style tables.
function jQueryUIStyling() {
$('input:button, input:submit').button();
$('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
$('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
jQueryTableStyling();
} // end of jQueryUIStyling
function jQueryTableStyling() {
$('.webgrid').addClass('ui-grid-content ui-widget-content');
$('.webgrid-header').addClass('ui-state-default');
$('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
} // end of jQueryTableStyling
});
</script>
<script type="text/javascript">
function filterGrid() {
var filters = getFilterVals();
$.ajax({
url: '#Url.Action("Index", "UserManager")',
type: "POST",
async: true,
dataType: "html",
data: "alfConnect=" + filters.alfConnect + "&" + "alfIntelligence=" + filters.alfIntelligence + "&" + "brad=" + filters.brad,
success: function (data) {
$('#webgrid-wrapper').empty().html(data);
// $('#webgrid-wrapper').html(data);
}
});
}
function getFilterVals() {
filters = new Object();
if ($('.webgrid-filter #chkFilterAlfIntell').is(':checked')) {
filters.alfIntelligence = 1;
}
else {
filters.alfIntelligence = 0;
}
if ($('.webgrid-filter #chkFilterAlfConn').is(':checked')) {
filters.alfConnect = 1;
}
else {
filters.alfConnect = 0;
}
if ($('.webgrid-filter #chkFilterBrad').is(':checked')) {
filters.brad = 1;
}
else {
filters.brad = 0;
}
return filters;
}
function logUserOff(url) {
var answer = confirm('Are you sure you want to save this data?')
if (answer) {
// alert(url + ": " + value);
$.ajax({
url: url,
type: "POST"
// data: value
}).done(function () {
$(this).addClass("done");
});
return true;
}
else {
return false;
}
};
</script>
Partial view with hidden fields
#model UserManager.Models.webgrid_validation
<b>#Html.Label("Select a filter: ")</b>
<br />
#Html.Label("Toggle ALF Intelligence users:")
#Html.CheckBoxFor(model => model.chkBoxAlfIntelligence, new
{
id = "chkFilterAlfIntell",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnAlfIntelligence", Model.chkBoxAlfIntelligence)
#Html.Label("Toggle ALF Connect users:")
#Html.CheckBoxFor(model => model.chkBoxAlfConnect, new
{
id = "chkFilterAlfConn",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnAlfConnect", Model.chkBoxAlfConnect)
#Html.Label("Toggle BRAD users:")
#Html.CheckBoxFor(model => model.chkBoxBrad, new
{
id = "chkFilterBrad",
onclick = "filterGrid()",
#checked = "checked"
})
#Html.Hidden("hdnBrad", Model.chkBoxBrad)
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;
namespace UserManager.Controllers
{
public class UserManagerController : Controller
{
//
// GET: /UserManager/
public ActionResult Index()
{
try
{
var model = new UserManagerTestEntities().vw_UserManager_Model;
return View(model.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
[HttpPost]
public ActionResult Index(int alfConnect, int alfIntelligence, int brad)
{
List<UserManager.Models.vw_UserManager_Model> modelList = DAL.getGrid(alfConnect, alfIntelligence, brad);
switch (alfConnect)
{
case 1:
ViewData["chkBoxAlfConnect"] = 1;
break;
case 0:
ViewData["chkBoxAlfConnect"] = 0;
break;
}
switch (alfIntelligence)
{
case 1:
ViewData["chkBoxAlfIntelligence"] = 1;
break;
case 0:
ViewData["chkBoxAlfIntelligence"] = 0;
break;
}
switch (brad)
{
case 1:
ViewData["chkBoxBrad"] = 1;
break;
case 0:
ViewData["chkBoxBrad"] = 0;
break;
}
return PartialView("~/Views/Partial/_WebGridUserManager.cshtml", modelList);
}
[ChildActionOnly]
public ActionResult _WebGridFilter ()
{
UserManager.Models.webgrid_validation model = new webgrid_validation();
return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
}
//public ActionResult _WebGridFilter(int alfConnect, int alfIntelligence, int brad)
//{
// UserManager.Models.webgrid_validation model = new webgrid_validation();
//switch (alfConnect)
//{
// case 1:
// model.chkBoxAlfConnect = true;
// break;
// case 0:
// model.chkBoxAlfConnect = false;
// break;
//}
//switch (alfIntelligence)
//{
// case 1:
// model.chkBoxAlfIntelligence = true;
// break;
// case 0:
// model.chkBoxAlfIntelligence = false;
// break;
//}
//switch (brad)
//{
// case 1:
// model.chkBoxBrad = true;
// break;
// case 0:
// model.chkBoxBrad = false;
// break;
//}
// return PartialView("~/Views/Partial/_WebGridFilter.cshtml", model);
//}
#region ajaxMethods
public ActionResult LookUpGroupName(string q, int limit)
{
try
{
//TODO: Map list to autocomplete textbox control
DAL d = new DAL();
List<string> groups = d.groups();
var GroupValue = groups
.Where(x => x.Contains(q))
.OrderBy(x => x)
.Take(limit)
.Select(r => new { group = r });
// Return the result set as JSON
return Json(GroupValue, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
public ActionResult LogUserOff(string userid)
{
try
{
//TODO: Map list to autocomplete textbox control
return View();
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
//[HttpPost]
//public ActionResult FilterGrid(int alfConnect, int alfIntelligence, int brad)
//{
// List<UserManager.Models.vw_UserManager_Model> modelList = DAL.getGrid(alfConnect, alfIntelligence, brad);
// return PartialView("_WebGridUserManager", modelList);
//}
#endregion
#region crud
public ActionResult CreateUser()
{
//var data = new UserManager.Models.UserManagerTestEntities();
ViewBag.Message = "Create New User";
var model = new vw_UserManager_Model();
return View(model);
}
[HttpPost]
public ActionResult CreateUser (vw_UserManager_Model model)
{
int outcome = 0;
if (ModelState.IsValid)
{
//var data = new UserManager.Models.UserManagerTestEntities();
// Pass model to Data Layer
outcome = UserManager.DAL.CreateUser(model, outcome);
//data.SaveChanges();
}
if (outcome > 0) // Success
{
return RedirectToAction("showSuccess", model);
}
else // Failure
{
return RedirectToAction("showError", new { ErrorMessage = "Error" });
}
}
public ActionResult EditUser(Guid userid, string salutation, string firstname, string lastname, string password, Nullable<bool> isactive, Nullable<int> maxconcurrentusers, string email, string module, string group)
{
vw_UserManager_Model editUser = new vw_UserManager_Model();
editUser.userid = userid;
editUser.salutation = salutation;
editUser.firstname = firstname;
editUser.lastname = lastname;
editUser.password = password;
editUser.isactive = isactive;
editUser.MaxConcurrentUsers = maxconcurrentusers;
editUser.email = email;
editUser.module_name = module;
editUser.group_name = group;
return View(editUser);
}
[HttpPost]
public ActionResult EditUser(vw_UserManager_Model editUser)
{
if (ModelState.IsValid)
{
UserManager.DAL.EditUser(editUser);
}
return View();
}
public ActionResult DeleteUser(Guid userid, string username, string salutation, string firstname, string lastname, string password, bool isactive, string email, string module, string group)
{
vw_UserManager_Model DeleteUser = new vw_UserManager_Model();
DeleteUser.userid = userid;
DeleteUser.UserName = username;
DeleteUser.salutation = salutation;
DeleteUser.firstname = firstname;
DeleteUser.lastname = lastname;
DeleteUser.password = password;
DeleteUser.isactive = isactive;
DeleteUser.email = email;
DeleteUser.module_name = module;
DeleteUser.group_name = group;
return View(DeleteUser);
}
[HttpPost]
public ActionResult DeleteUser(vw_UserManager_Model deleteUser)
{
if (ModelState.IsValid)
{
UserManager.DAL.DeleteUser(deleteUser);
return RedirectToAction("showSuccess", new { SuccessMessage = "Success" });
}
return View();
}
#endregion crud
#region successErrorHandling
public ActionResult showError(List<string> ErrorMessage)
{
ViewBag.ErrorMessage = ErrorMessage[0];
return View("ErrorMessageView");
}
public ActionResult showSuccess(vw_UserManager_Model model)
{
return View("SuccessMessageeView", model);
}
#endregion
}
}
My question is how to use hidden fields to maintain state of checkboxes between page request?
you could remove the form and send data to the controller as JSon values, and thus refresh only the part of the page that needs to be refreshed.
Regards

Hide Route values when using RedirectToAction

[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HomeOfficeViewModel viewModel)
{
return RedirectToAction("SearchResults", "HomeOffice", viewModel);
}
public ActionResult SearchResults(HomeOfficeViewModel viewModel)
{
if (viewModel.FirstName != null && viewModel.LastName == null && viewModel.FullSsn == null)
{
List<Domain.Model.PolicyHolder> ph = _policyHolderRepository.Where(x => x.FirstName == viewModel.FirstName).ToList();
if (ph.Count != 0)
{
var searchresults = from p in ph
select new SearchResultsViewModel
{
FullSsn = p.Ssn,
FullName = p.FirstName + " " + p.LastName,
UserId = p.UserId
};
TempData["SearchedItem"] = "<<< First Name >>> is '" + viewModel.FirstName + "'";
return View("SearchResults", new SearchResultsViewModel() {SearchResults = searchresults.ToList()});
}
else
{
ModelState.Clear();
ModelState.AddModelError("Error", "First Name searched does not exist in our records");
return View("Index");
}
}
else
{
return View();
}
}
values in the viewModel are being shown in the url like this
http://sample.url.com/HomeOffice/SearchResults?FirstName=testing
I should not show them in the url because I will be sending ssn. Is there a way to hide them or any better way to do this.
Thanks.
RedirectToAction will create a GET request to the named action (SearchResults in your case) which is probably trying to serialize your view model fields. Instead, you could use TempData
[HttpPost]
public ActionResult Index(HomeOfficeViewModel viewModel)
{
TempData["Field1"] = "Value1";
TempData["HomeOfficeViewModel1"] = viewModel;
return RedirectToAction("SearchResults", "HomeOffice", viewModel ?? null);
}
public ActionResult SearchResults(HomeOfficeViewModel viewModel)
{
string field1 = TempData["Field1"].ToString();
if(viewModel == null)
viewModel = TempData["HomeOfficeViewModel1"] as HomeOfficeViewModel;
return View(viewModel);
}

Resources