How to return top previous URL after Edit in ASP.NET Core - asp.net-core-1.0

I am using asp,net core and have used the tutorial to create sorted, paged and search page (Index). Once I edit an item from this page the controller always dumps me back to the default index page. How do I return to the previous URL. Many thanks.
Here is a section of my controller file.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, Bind("id,UserPassword,user")] UserProfiles userProfiles)
{
var users = from u in _context.UserProfiles
select u;
if (id != userProfiles.id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(userProfiles);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserProfilesExists(userProfiles.id))
{
return NotFound();
}
else
{
throw;
}
}
// ***************
// Redirect to the previous URL,i.e. the Index
return Redirect(TempData["PreviousURL"].ToString()) ;
}
return View(userProfiles);
}
public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
// paging
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
// search
ViewData["CurrentFilter"] = searchString;
var users = from u in _context.UserProfiles
select u;
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(u => u.user.Contains(searchString)
);
}
//sort
switch (sortOrder)
{
case "name_desc":
users = users.OrderByDescending(u => u.user);
break;
default:
users = users.OrderBy(s => s.user);
break;
}
// ***************
// store the current path and query string in TempData["PreviousURL" session variable
TempData["PreviousURL"] = HttpContext.Request.Path.ToString() + HttpContext.Request.QueryString.ToString();
return View(await PaginatedList<UserProfiles>.CreateAsync(users.AsNoTracking(), page ?? 1, pageSize));
}
This is my first MVC project.

It depends on your logic where controller takes you after saving data.
You need to pass search, sort and paging related data to controller when saving data. You can send them as part of extra post data, as query string parameters or as part of the model itself which is being posted.
After saving data retrieve data based on those parameters and populater your view with that paged, filtred and sorted data.

I solved my problem with the use of session variables: ViewData, ViewBag and TempData. The following two pages were very useful:
https://www.codeproject.com/Articles/476967/What-is-ViewData-ViewBag-and-TempData-MVC-Option
http://andrewlock.net/an-introduction-to-session-storage-in-asp-net-core/
Please see edited question above for the solution.

Related

Extend Umbraco back office search to search custom proerties not just title

What I would like to do is be able to type an custom property within the back office search. e.g. put the ISBN into the search field and have the results shown currently it always returns "no items found" as the search will only show results for the title node.
How do I enable the content search as seen in the image to search the data in the custom fields?
The data is in the internal index, I have checked the index is working and can see the result with "Examine Management" if I search via the custom data.
The solution is what I used to extend the search
https://dev.to/skttl/how-to-customize-searching-in-umbraco-list-views-1knk
Add a new file in the App_Code (SearchExtender)
using System.Linq;
using Examine;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Web;
using Umbraco.Web.Editors;
using Umbraco.Web.Models.ContentEditing;
namespace SearchExtender
{
public class CustomListViewSearchController : ContentController
{
public CustomListViewSearchController(PropertyEditorCollection propertyEditors, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper)
: base(propertyEditors, globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper)
{
}
public PagedResult<ContentItemBasic<ContentPropertyBasic>> GetChildrenCustom(int id, string includeProperties, int pageNumber = 0, int pageSize = 0, string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, bool orderBySystemField = true, string filter = "", string cultureName = "")
{
// get the parent node, and its doctype alias from the content cache
var parentNode = Services.ContentService.GetById(id);
var parentNodeDocTypeAlias = parentNode != null ? parentNode.ContentType.Alias : null;
// if the parent node is not "books", redirect to the core GetChildren() method
if (parentNode?.ContentType.Alias != "books")
{
return GetChildren(id, includeProperties, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter);
}
// if we can't get the InternalIndex, redirect to the core GetChildren() method, but log an error
if (!ExamineManager.Instance.TryGetIndex("InternalIndex", out IIndex index))
{
Logger.Error<CustomListViewSearchController>("Couldn't get InternalIndex for searching products in list view");
return GetChildren(id, includeProperties, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter);
}
// find children using Examine
// create search criteria
var searcher = index.GetSearcher();
var searchCriteria = searcher.CreateQuery();
var searchQuery = searchCriteria.Field("parentID", id);
if (!filter.IsNullOrWhiteSpace())
{
searchQuery = searchQuery.And().GroupedOr(new [] { "nodeName", "isbn" }, filter);
}
// do the search, but limit the results to the current page 👉 https://shazwazza.com/post/paging-with-examine/
// pageNumber is not zero indexed in this, so just multiply pageSize by pageNumber
var searchResults = searchQuery.Execute(pageSize * pageNumber);
// get the results on the current page
// pageNumber is not zero indexed in this, so subtract 1 from the pageNumber
var totalChildren = searchResults.TotalItemCount;
var pagedResultIds = searchResults.Skip((pageNumber > 0 ? pageNumber - 1 : 0) * pageSize).Select(x => x.Id).Select(x => int.Parse(x)).ToList();
var children = Services.ContentService.GetByIds(pagedResultIds).ToList();
if (totalChildren == 0)
{
return new PagedResult<ContentItemBasic<ContentPropertyBasic>>(0, 0, 0);
}
var pagedResult = new PagedResult<ContentItemBasic<ContentPropertyBasic>>(totalChildren, pageNumber, pageSize);
pagedResult.Items = children.Select(content =>
Mapper.Map<IContent, ContentItemBasic<ContentPropertyBasic>>(content))
.ToList(); // evaluate now
return pagedResult;
}
}
}
change requests for /umbraco/backoffice/UmbracoApi/Content/GetChildren (the default endpoint for child nodes), and change it to my newly created one, which is located at /umbraco/backoffice/api/CustomListViewSearch/GetChildrenCustom.
This is done easily by adding a js file containing an interceptor like this.
Add file to /App_Plugins/CustomListViewSearch/CustomListViewSearch.js
angular.module('umbraco.services').config([
'$httpProvider',
function ($httpProvider) {
$httpProvider.interceptors.push(function ($q) {
return {
'request': function (request) {
// Redirect any requests for the listview to our custom list view UI
if (request.url.indexOf("backoffice/UmbracoApi/Content/GetChildren?id=") > -1)
request.url = request.url.replace("backoffice/UmbracoApi/Content/GetChildren", "backoffice/api/CustomListViewSearch/GetChildrenCustom");
return request || $q.when(request);
}
};
});
}]);
a package.manifest file in my App_Plugins folder.
{
"javascript": [
"/App_Plugins/CustomListViewSearch/CustomListViewSearch.js"
]
}
If the node Alais isnot working make sure its set in the documnt type (far right on document type name)

I wanted to update an existing record in asp.net mvc using Entity framework

I wanted to check if the productDiscount entity is already exist in the database, if it is exist then I wanted to update it. But instead of updating the entity the following code adds a new one. How to solve this problem..
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ProductDiscount(ProductDiscount productDiscount)
{
if (!ModelState.IsValid)
{
var viewModel = new ViewModelProductDiscount()
{
Products = _context.Products.ToList()
};
return View(viewModel);
}
var id = productDiscount.ProductId;
var disInDb = _context.ProductDiscounts.FirstOrDefault(p => p.ProductId == id);
if (disInDb==null)
{
_context.ProductDiscounts.Add(productDiscount);
_context.SaveChanges();
}
else
{
_context.ProductDiscounts.Add(disInDb);
_context.SaveChanges();
return Content(disInDb.Id.ToString());
}
return RedirectToAction("Products");
}
from the else block remove _context.ProductDiscounts.Add(disInDb); Just map the productDiscount values into disInDb and then _context.SaveChanges();
Like
else
{
disInDb.Name = productDiscount.Name;
disInDb.Discription = productDiscount.Discription;
_context.SaveChanges();
}
I don't really know how your ProductDiscount object looks like so I will assume your object props but it should give you an idea of how to update the record. Inside your else this line _context.ProductDiscounts.Add(disInDb); is what is causing the issue. Instead you want to do the following inside the else block
else
{
disInDb.DiscountCode = "somecode"; //change this to the correct prop name which needs updating
disInDb.DiscountProductName = "somename"; //change this to the correct prop name which needs updating
_context.SaveChanges();
}

How to intercept hardware Bar Back Button Clicked in Android in Xamarin Forms?

I want to intercept hardware back buttion in my Xamarin Forms Portable app, At First I have login page,You have to login and it will navigate to my Homepage2.. after going to my homepage2, when i click on my hardware backbutton...It goes to my login page or the pages i opened previously.. I want to Prevent it. Can anyone please resolve me this issue..
here is my login page
public LoginPage()
{
InitializeComponent();
}
public async void LoginBtn_Clicked(object sender, EventArgs e)
{
if (UserName.Text == null || password1.Text == null)
{
DisplayAlert("Alert ! ", "Please Enter UserName Or/Password!", "OK");
}
else
{
string uname = UserName.Text;
string pswd = password1.Text;
LoginService objservice = new LoginService();
LoginTokenModel result = await objservice.GetLogin(uname, pswd);
LoginTokenModel logintokenmodel = new LoginTokenModel();
logintokenmodel.User_Id = result.User_Id;
var Login_Token = result.Login_Token;
int user_Id = result.User_Id;
if (uname == result.User_Nmae)
{
// HomePage2 HOMEPge = new HomePage2();
await Navigation.PushModalAsync(new HomePage2(user_Id));
}
else
{
DisplayAlert("Alert ! ", "Invalid Credentials!", "OK");
}
}
}
Replace the App's MainPage with your Homepage2.
as you are not coming back on Login page you don'n want it in the NavigationStack.
This is what I do on successful Login:
if (uname == result.User_Nmae)
{
App.Current.MainPage = new HomePage2(user_Id);
}
In addition you can also keep this user_Id stored for the second time when the user enters again in application properties and check if the user_Id exists or not, if it does just navigate to Homepage2
Application.Current.Properties["id"] = user_Id;
in App.cs onStart
if (Application.Current.Properties.ContainsKey("id"))
{
var user_Id = Application.Current.Properties["id"] as string;
MainPage.Navigation.PushModalAsync(new Views.Homepage2(user_Id ));
}
else
{
MainPage.Navigation.PushModalAsync(new Views.Login());
}

Session variable fine in one action, null in next

I have a simple application. When a user logs in it creates a session variable and redirects them to another controller that pull up some info from the database. I need to store this to a session variable then return it to the view. The initial part is fine, it returns it and I see the information. However, when I try to create a search query it returns that the session is null even though I never clear it.
public ActionResult ShowCourses()
{
if (Session["Username"] != null)
{
string Username = Session["Username"].ToString();
using (DefaultConnection db = new DefaultConnection())
{
var model = from c in db.Courses
where c.Username == Username
select c;
Session["Courses"] = model.ToList();
var Courses = Session["Courses"];
return View(Courses);
}
}
else
{
return RedirectToAction("Login", "Users");
}
}
But when I try to run a search query to loop through the session, it brings back that Courses is null. The problem is that coursesQuery returns null and I'm not sure why.
public ActionResult SearchCourses(string query)
{
if (Session["Username"] != null)
{
var coursesQuery = Session["Courses"] as IEnumerable<Course>;
if (coursesQuery != null)
{
// Do Something
}
}
}
You did a .ToList() on the course colleciton before setting to Session.
Try this. Use List<Course> when you read it back.
if (Session["Courses"] != null)
{
var coursesQuery = (List<Course>) Session["Courses"];
}

Non-unique ldap attribute name with Unboundit LDAP SDK

I am attempting to retrieve objects having several attributes with the name from netscape LDAP directory with LDAP SDK from Unboundit. The problem is that only one of the attributes are returned - I am guessing LDAP SDK relays heavily on unique attribute names, is there a way to configure it to also return non-distinct attributes as well?
#Test
public void testRetrievingUsingListener() throws LDAPException {
long currentTimeMillis = System.currentTimeMillis();
LDAPConnection connection = new LDAPConnection("xxx.xxx.xxx", 389,
"uid=xxx-websrv,ou=xxxx,dc=xxx,dc=no",
"xxxx");
SearchRequest searchRequest = new SearchRequest(
"ou=xxx,ou=xx,dc=xx,dc=xx",
SearchScope.SUB, "(uid=xxx)", SearchRequest.ALL_USER_ATTRIBUTES );
LDAPEntrySource entrySource = new LDAPEntrySource(connection,
searchRequest, true);
try {
while (true) {
try {
System.out.println("*******************************************");
Entry entry = entrySource.nextEntry();
if (entry == null) {
// There are no more entries to be read.
break;
} else {
Collection<Attribute> attributes = entry.getAttributes();
for (Attribute attr : attributes)
{
System.out.println (attr.getName() + " " + attr.getValue());
}
}
} catch (SearchResultReferenceEntrySourceException e) {
// The directory server returned a search result reference.
SearchResultReference searchReference = e
.getSearchReference();
} catch (EntrySourceException e) {
// Some kind of problem was encountered (e.g., the
// connection is no
// longer valid). See if we can continue reading entries.
if (!e.mayContinueReading()) {
break;
}
}
}
} finally {
entrySource.close();
}
System.out.println("Finished in " + (System.currentTimeMillis() - currentTimeMillis));
}
Non-unique LDAP attributes are considered multivalued and are reperesented as String array.
Use Attribute.getValues() instead of attribute.getValue.

Resources