404 error although route exists in laravel 6 - laravel-6

I have routes like this: Route::resource('admin/post', 'Admin\PostsController');
Route for edit post exists but I get 404 error. I list all routes php artisan r:l and it shows me the post.edit but it doesn't show me edit page.
in web.php
Route::resource('admin/post', 'Admin\PostsController');
in Admin\PostsController
public function edit($id)
{
$post = Post::findOrFail($id);
return view('backend.posts.edit', compact('post'));
}
in index.php
<a href="{{route('post.edit', $post->id)}}" class="btn btn-sx btn-primary">
<i class="fa fa-edit"></i>
</a>
this is the error of edit page

Related

How to delete from a database in Ajax?

I'm sure there are similar questions, but I searched both here and on Google and found no answer.
I have a list of products in the database. And I have a method that delete the current product by button. And it works great!
The problem starts when I try to make the button not POSTBACK
I know the problem is with the RETURN but if I do not write it, I have an error message because my method is - async Task
For what I need to change the method so that it works without changing the URL / postback?
index.cshtml-
<ul class="list-group list-group-lg list-group-flush list my--4">
#foreach (var prod in Model.ProductList)
{
<li class="list-group-item px-0">
<div class="row align-items-center">
<div class="col-auto">
<span class="avatar avatar-lg">
תמונה
</span>
</div>
<div class="col ml--2">
<h4 class="card-title mb-1">
<a href="#!">
#Html.DisplayFor(modelItem => prod.ProductName)
</a>
</h4>
<p class="card-text small text-muted mb-1">
אימייל
</p>
</div>
<div class="col-auto">
<form method="post">
<input type="submit" asp-page-handler="Delete" value="Delete" asp-route-id="#prod.Id" data-ajax="true" data-ajax-success="deleteItem(this)" />
</form>
</div>
</div>
</li>
}
Index.cshtml.cs-
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
Product currentProduct = new Product();
foreach (var item in _context.Products)
{
if (item.Id==id)
{
currentProduct = item;
break;
}
}
_context.Products.Remove(currentProduct);
_context.SaveChanges();
return RedirectToPage("./Index");
}
Based on your code, we can find that it will return HTTP 302 redirect response status code while you make AJAX request from client side. Please note that AJAX can not automatically redirect to that page, normally we do not return a redirect response to AJAX client.
As #schwartz721 mentioned, if possible, you can try to modify the handler to return JsonResult or OkResult etc rather than RedirectToPage, then you can handle response in success callback.
Besides, if you indeed want to do AJAX submission and redirect user to index page after user delete a product, you may need to do redirection on client side, like below.
window.location.href = url_here;

sitefinity update view from action method

I am using this form to post data to the controller once the data is saved I wanted to display this Success view but I am getting a 404 page not found. Any idea why I am getting this error?
View
#using (Html.BeginFormSitefinity("Save", "Preference", FormMethod.Post, new { id = "preferencesForm" }))
{
<div class="row">
<div class="text-center">
<button type="submit" class="btn btn-primary px-4 float-center">Save</button>
</div>
</div>
controller
public ActionResult Save(PreferenceViewModel model)
{
SaveData(model);
return View("~/Mvc/Views/Preference/Success.cshtml");
}
Does your code hit the Save method? I don't see it marked with the [HttpPost] attribute.
Also, if this is your Preference widget, then you can simply use this:
return View("Success");
Sitefinity will look for success.cshtml in the correct folder.

Navigate to new view on button click in ASP.NET Core 3.1 MVC

I am trying to navigate the user to a new page with a button click. I am having issues with rendering the new view. Any time I do click on the button, I either get an error for a dropdown on my page, or I get the home page view but with my desired route in the URL. I wanted to note that the user will be navigating to this page from the home page, which I made into my new landing page on the app. I wanted to point that out in case something I did here can be modified.
How I created a new landing page
I want to navigate from my landing page to my book inventory page.
My View (On the landing page):
<form method="post" asp-controller="Home" asp-action="Home" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="#(new SelectList(ViewBag.message, "ID", "bookName"))">
</select>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
<div class="row">
<div class="form-group">
<a asp-controller="BookInventory" asp-action="Index">
<input type="button" value="Book Inventory Page" />
</a>
</div>
</div>
My Controller (On my landing page)
public void GetBooksDDL()
{
List<BookModel> bookName = new List<BookModel>();
bookName = (from b in _context.BookModel select b).ToList();
bookName.Insert(0, new BookModel { ID = 0, bookName = "" });
ViewBag.message = bookName;
}
[HttpGet("[action]")]
[Route("/Home")]
public IActionResult Home()
{
GetBooksDDL()
return View();
}
My Controller (On my book inventory page):
[HttpGet("[action]")]
[Route("/Index")]
public IActionResult Index()
{
return View();
}
I wanted to note that my breakpoint on my book inventory controller does hit the 'return View()', but it will still render the items from the homepage.
The error I get with the book dropdown says:
ArgumentNullException: Value cannot be null. (Parameter 'items')
Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField).
I'm wondering why I'm getting this error when I'm trying to navigate to a different page. Since this is the new landing page, is it possible that it is passing along all of its data to the rest of the pages?
ArgumentNullException: Value cannot be null. (Parameter 'items')
Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.ctor(IEnumerable
items, string dataValueField, string dataTextField, IEnumerable
selectedValues, string dataGroupField).
About this error, it means that you didn't set the value for the select element, before return to the view, please check the ViewBag.message value, make sure it contains value.
Note: Please remember to check the post method, if the Http Get and Post method returns the same page, make sure you set the ViewBag.message value in both of the action methods.
I wanted to note that my breakpoint on my book inventory controller
does hit the 'return View()', but it will still render the items from
the homepage.
In the BookInventory Controller Index action method, right click and click the "Go to View" option, make sure you have added the Index view.
Based on your code, I have created a sample using the following code, it seems that everything works well.
Code in the Home Controller:
[HttpGet("[action]")]
[Route("/Home")]
public IActionResult Home()
{
GetBooksDDL();
return View();
}
[HttpPost("[action]")]
[Route("/Home")]
public IActionResult Home(BookModel book, string bookName)
{
GetBooksDDL();
//used to set the default selected value, based on the book id (bookName) to find the book.
List<BookModel> booklist = (List<BookModel>)ViewBag.message;
book = booklist.Find(c => c.ID == Convert.ToInt32(bookName));
return View(book);
}
Code in the Home view:
#model BookModel
#{
ViewData["Title"] = "Home";
}
<h1>Home</h1>
<form method="post" asp-controller="Home" asp-action="Home" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="#(new SelectList(ViewBag.message, "ID", "bookName", Model == null? 0:Model.ID))">
</select>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
<div class="row">
<div class="form-group">
<a asp-controller="BookInventory" asp-action="Index">
<input type="button" value="Book Inventory Page" />
</a>
</div>
</div>
Code in the BookInventory controller:
public class BookInventoryController : Controller
{
[HttpGet("[action]")]
[Route("/Index")]
// GET: BookInventory
public ActionResult Index()
{
return View();
}
The screenshot as below:
If still not working, please check your routing configuration, perhaps there have some issue in the routing configure.
Your anchor tag formation is incorrect. You cannot write a button within anchor tag.
Do something like this:
<a asp-action="Index" asp-controller="BookInventory" class="btn btn-primary">Book Inventory Page</a>
Here the class will help your anchor tag look like buttons. I hope you have used bootstrap in your project. If not, then use it.
Hope this helps.
Here is another simple way:
<button type="button" class="btn" onclick="window.location.href = '/YourPage'">Button Title</button>

How to create a button that will go to a razor page when clicked ("Razor page" in dotnet core 2)

I can use an anchor tag helper to go to a different razor page (from an existing razor page) e.g. this works:
<a asp-page="./EditReport" asp-route-id="#report.IntegrityReportId" class="btn fa fa-edit"></a>
How can I get a similar thing to work but using a button. I have tried:
<button type="button" asp-route-data="#report.IntegrityReportId" asp-route="EditReport">EditReport</button>
But the page never loads. I also tried using the page handler with different variations of:
<input type="button" asp-page-handler="EditReport" asp-route="#report.IntegrityReportId"/>
and associated (in the page cs file):
public ActionResult OnEditReport(int id)
{
return RedirectToPage("./EditReport", id);
}
but this method never gets called (I've also tried naming method OnPostEditReport but same problem.
If it helps, my original NON- dotnet core app worked fine with:
<button type="button" title="Edit report" class="btn btn-datatable fa fa-edit" onclick="location.href = '#Url.Action("EditReport", "Home", new {id = report.IntegrityReportID})'"></button>
Any help is appreciated.Thanks.
I managed to get the effect I needed by using the below anchor - so it looks like a button..
<a asp-page="./EditReport" asp-route-id="#report.IntegrityReportId" class="btn btn-default"><i class="fa fa-edit"></i></a>
The solution below worked for me in my ASP.NET Core 3.1 project:
<a class="btn btn-primary btn-sm" asp-page="./Edit" asp-route-id="#item.Id"><i class="fas fa-user"></i> Edit</a>
The highlighted code above is all on one line, just the way stack overflow is presenting the answer. Note I chose to display the icon before the text in the button, then I added a single chazr space before the button label 'Edit' just so the button looks a little nicer.
You can not use just a button which will redirect to an other razor page without javascript. You can use a submit button inside a form tag in order to redirect to an other razor page. The following example demonstrates how to make a GET redirect which will redirect to the About page:
<form method="get">
<button type="submit" asp-page="./About">Click me to go to the About page</button>
</form>
if you want a POST request use the following code:
<form method="post">
<button type="submit" asp-page="./About">Click me to go to the About page</button>
</form>
In both cases you can define routing values or handlers in order to cover the requirements.
I hope it helps.
I know its a year late, but you have to remove 'type="button"', also try removing '.' from asp-page="./EditReport".
BR.
This works in ASPNET Core 3.1.
<form method="get" action="/myRazorPage">
<button type="submit">Join Now</button>
</form>
using button:
<button type="button" class="btn" onclick="window.location.href = '/YourPage'">Button Title</button>

data-ajax-update and data-ajax-mode="replace" not working in dotnet core jquery unobtrusive ajax

I have an anchor which should replace a grid with a partial view .
<a class="btn btn-primary"
data-ajax="true"
data-ajax-method="GET"
data-ajax-mode="replace"
data-ajax-update="content"
data-ajax-url="#Url.Action("add","user")"> Create User </a>
<div class="row table-area">
<div class="col-md-12" id="content">
#Html.AjaxGrid(Url.Action("results", "user"))
</div>
</div>
I see it calls the user action with partial view but it never updates the section with id="content".
Here is my controller method -
[Route("add")]
public IActionResult AddUser()
{
return PartialView("Partials/AddUser",new RegisterViewModel());
}
Ideally it should replace the grid content with the partial view altogether but it is not replacing . The response status is 200 and I can see that the contents are being returned in response . Anybody has any idea what is the issue here ?
Change data-ajax-update="content" to data-ajax-update="#content"
Rather than using data-ajax-url, use the asp-controller and asp-action and the #content should work.
<a class="btn btn-primary" asp-controller="user" asp-action="add"
data-ajax="true"
data-ajax-method="GET"
data-ajax-mode="replace"
data-ajax-update="#content">Create User</a>