ActionLink doesn't work - razor

I'm pretty sure that I'm doing something really stupid. Please have a look and let me know what I'm doing wrong.
Here is my ActionLink
#Html.ActionLink("Edit","Edit","UserProfile", new { id = Model.ApplicationUserId },null)
When I click this it throws the bad request exception and also I noticed the url is
https://localhost:44304/UserProfile/Edit/92b1347c-c9ec-4728-8dff-11bc9f935d0b
not
https://localhost:44304/UserProfile/Edit?userId=92b1347c-c9ec-4728-8dff-11bc9f935d0b
I have a HTTPGET Edit method in my controller and it takes UserId. When I pass the route values manually it works.Please help me.
Your help is much appreciated and someday, will pay it forward.
Thanks!
Cheers!

If the parameter you are expecting is userId, then use the #Html.ActionLink like this:
#Html.ActionLink("Edit","Edit","UserProfile", new { userId = Model.ApplicationUserId },null)
If you pass the parameter with name id, then the MVC will route like you mentioned:
https://localhost:44304/UserProfile/Edit/92b1347c-c9ec-4728-8dff-11bc9f935d0b
Which is great, but your method should be something expecting the parameter with the appropriate name:
// GET: /UserProfile/Edit/{id}
public ActionResult Edit(String id){
//your code
return View();
}
If you have some time, check out this ASP.NET MVC Routing Overview with a lot more details.

You need change parameter for your controller action Edit from userId to id - best variant.
public Edit(int id)
{
}
Or
#Html.ActionLink("Edit","Edit","UserProfile", new { userId = Model.ApplicationUserId },null)

Related

I want to send two parameters using href through anchor tag in ASP.NET MVC

This code is not hitting the action method. Can you suggest the correct code?
College is my controller and Details is my action name.
Try replacing this line of code:
With this line of code:
#Html.ActionLink("View Details","Details","Colleges",new { id = item.Id, CountryId = item.CountryId },null)
Hopefully, your action method header in Colleges controller looks something like this:
[HttpGet]
public IActionResult Details(int id, int countryId)
Goodluck!

.NET Core 2.1 - Accessing Config/usermanager in a static helper

I've recently moved from MVC5 over to .NET Core 2.1 (MVC). Can anyone help me with this please.
I have my ApplicationUser and I've extended the model/table to store the user's FirstName.
In the View, I want to be able to output the current user firstname value.
User in the view is a ClaimsPrincipal so I need to go off to the DB to grab the value I need or access UserManager to get it.
Now, I know I can get that in the controller but I don't want to have to create a JQuery call to grab it every time I need it.
What I do want is to be able to access it server side, ideally via a static helper class.
In the MVC5 I'd have a helper to do the job no problem. Something like this for example:
public static string GetCurrentUserFirstName()
{
string _usrRef = HttpContext.Current.User.Identity.GetUserId();
var user = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(_usrRef);
return user.FirstName;
}
However, .NET Core doesn't work that way.
In a controller I could say:
var user = await _userManager.GetUserAsync(User);
string firstName = user.FirstName;
or I could go off to the DB via a call using Dapper w/ my connection string.
I can't inject the UserManager or ConnectionStrings into the helper via the constructor as it is static.
Is there a way to access either of those in this static helper?
It's the little changes that get you the most!
Thanks to #Kirk Larkin - I've found the solution.
I have to admit, it feels a little more convoluted having to pass things around to gain access to them but this is a good, working solution.
The View:
#using Microsoft.AspNetCore.Identity
#using MyApplication.Helpers
#inject UserManager<ApplicationUser> UserManager
<div>
#await MyHelper.GetLoggedInUserFirstName(UserManager, User)
</div>
The MyHelper file:
public static async Task<string> GetLoggedInUserFirstName(UserManager<ApplicationUser> userManager, ClaimsPrincipal user)
{
string output = "";
try
{
var currentUser = await userManager.GetUserAsync(user);
if(currentUser!=null)
{
output = currentUser.FirstName ?? currentUser.Email;
}
}
catch(Exception e) { }
return output;
}

Like operator not working, using spring mvc and hibernate

Ok, so I'm still somewhat of a newbie to Java and hibernate and I'm trying to search for a question/answer set in my database, and I can pull up the set just fine if I type in the exact question, but when I use the like operator nothing works, and I'm really not sure what to do. I'm only searching for the question, and it's part of the same object as the answer, so I just pull up the answer with it as well.
Here's my code in my QuestionAnswerDao
public QuestionAnswerSet getQuestionAnswerSetByQuestion(String question)
{
Session session = (Session) em.getDelegate();
return (QuestionAnswerSet) session.createCriteria(QuestionAnswerSet.class).add(Restrictions.eq("question", "%"+question+"%")).uniqueResult();
}
Also here's my code in my controller
#RequestMapping(value="search", method=RequestMethod.GET)
public String searchGet (ModelMap model, HttpServletRequest request)
{
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "app/search";
}
#RequestMapping(value="search", method=RequestMethod.POST)
public String searchPost (#ModelAttribute("searchForm") SearchForm searchForm, ModelMap model, HttpServletRequest request)
{
QuestionAnswerSet questionAnswerSetByQuestion = questionAnswerDao.getQuestionAnswerSetByQuestion(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "app/search";
}
If anyone could help me out with this that would be great, thanks.
I don't see a "like" in your example but I assume you simply need to change
Restrictions.eq ro Restrictions.like.
So if using Hibernate 4.3 this would be this method:
https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/criterion/Restrictions.html#like(java.lang.String, java.lang.Object)
I think a bit worrying is the "uniqueResult" afterwards, if you search with a wildcard I would always assume there might be more then one result. And in case there is the uniqueResult method might throw an Exception.
Also it always helps to enable "show_sql" in the Hibernate config to see the actual sql generated by Hibernate during development.

MVC, How to read rendered HTML in a controller?

Maybe it´s a strange question, but imagine this:
//We all know that View is a method...
public ActionResult Something()
{
return View("index");
}
But what if I step before this method to perform some stats
public ActionResult Something()
{
return PerformStats(View("index"));
}
I will have a private method like this:
private ActionResult PerformStats(ViewResult viewResult)
{
//THIS IS WHAT I WANT TO ACCHIEVE:
//*********************************
var contentSent = viewResult.InnerHtml.Lengh; <<-- I wish!
return viewResult;
}
And latter, what i want to do, is to save that ammount of content sent to the client.
It doesn´t matter if it is the exactly quantity of html, even if I get the .count() of a json it will do the trick.
Is any way to know the rendered content on the controller?
Thanks!
OnActionExecuting: Called before action method executes. You can put stats related logic in there.
http://msdn.microsoft.com/en-us/library/system.web.mvc.iactionfilter.onactionexecuting(v=vs.98).aspx
OnActionExecuted: Called after action method executed.
http://msdn.microsoft.com/en-us/library/system.web.mvc.iactionfilter.onactionexecuted(v=vs.98).aspx
Within these methods you can access ActionExecuting and ActionExecutedContext
If you want to get a size of rendered HTML (partial or complete view), then you probably need to:
Find the view that you want to render
Store it in the string builder
Get its length
There is a question that explains how to render view as a string within the action method: In MVC3 Razor, how do I get the html of a rendered view inside an action?

Getting MVC2 Delete to work

Ok i have an mvc app. and im trying to get my delete to work. Basically i want it so when i click delete it takes me to a page saying "are you sure?" i have that working, the problem is catching the request and actually doing the delete. i tried diffrent methods. as below.
public ActionResult Delete(int id)
{
var something = friendsDB.Friends.Single(a => a.Id == id);
return View(something);
}
[HttpPost]
public ActionResult Delete(int id, string confirmButton)
{
var something = friendsDB.Friends.Single(a => a.Id == id);
// For simplicity, we're allowing deleting of albums
// with existing orders We've set up OnDelete = Cascade
// on the Album->OrderDetails and Album->Carts relationships
friendsDB.DeleteObject(something);
friendsDB.SaveChanges();
return View("Index");
}
That doesnt work cause, deleteobject and savechanges claim
"C:\Users\Mtszc\Documents\Visual
Studio
2010\Projects\Test\Test\Content\Controllers\DownloadsController.cs(36,23):
error CS1061: 'Test.Models.FriendsDB'
does not contain a definition for
'DeleteObject' and no extension method
'DeleteObject' accepting a first
argument of type
'Test.Models.FriendsDB' could be found
(are you missing a using directive or
an assembly reference?)"
the second thing i tried was
public ActionResult Delete(int id)
{
var something = friendsDB.Friends.Single(a => a.Id == id);
return View(something);
}
[HttpDelete]
public ActionResult Delete(Friend myFriend)
{
try
{
friendsDB.Friends.DeleteOnSubmit(myFriend);
friendsDB.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
that didnt work. it compiled but when i click delete, and it takes me to the page where i say im sure i want to delete, it returns view, which was the catch, meaning the try failed.
this is a simple sql database i made, Id, name, link. and im using linq to sql class. i c can create and view, but not delete.
Try something like this instead.
var rowToDelete = friendsDB.Friends.Single(a => a.ID == myFriend.ID);
friendsDB.Friends.DeleteOnSubmit(rowToDelete);
friendsDB.SubmitChanges();
That would be a simple way of taking care of the record delete with Linq. I apologize if the syntax isn't perfect since I'm writing it on the fly out of my head.
By the way there are some GREAT videos made by the guys over at Microsoft for learning ASP.NET MVC as well as LINQ. Check these out.
http://www.asp.net/mvc
Cheers
Ok for who ever views this i solved the problem. Through hours of digging, i solved the problem. For anyone who made a sql data base and made a model class for it using linq to sql this is how to get delete to work.
public ActionResult Delete(int id)
{
var something = friendsDB.Friends.Single(a => a.Id == id);
return View(something);
}
[HttpPost]
public ActionResult Delete(int id, string confirmButton)
{
var sigh = friendsDB.Friends.Single(a => a.Id == id);
try
{
friendsDB.Friends.DeleteOnSubmit(sigh);
friendsDB.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
with this, create a strongly typed delete view.
The error messages appear to be confusing you.
"C:\Users\Mtszc\Documents\Visual Studio 2010
\Projects\Test\Test\Content\Controllers\DownloadsController.cs(36,23): error
CS1061: 'Test.Models.FriendsDB' does not contain a definition for 'DeleteObject'
and no extension method 'DeleteObject' accepting a first argument of
type 'Test.Models.FriendsDB' could be found (are you missing a using directive
or an assembly reference?)"
Is not referring to the MVC Action, it is referring to your Test.Models.FriendsDB method call:
friendsDB.DeleteObject(something);
It sounds like you have not Defined the method "DeleteObject" on your friendsDB model or you do not have a overloaded method that accepts a 'Test.Models.FriendsDB' object type.
Secondly, don't confuse HTTP Methods (Get, Post, Put, Delete) with what you are trying to accomplish. "Put" and "Delete" are methods I don't believe web browsers use often if at all. Most requests are GET unless you are submitting a form, then they are POST. Adding the HttpDelete will most likely render that Action useless. If you only want a Delete action from a form submit then add HttpPost