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

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!

Related

ASP.NET Core MVC : load file inside Razor page

I am trying to make the terms and conditions page form my site. However, I am trying to provide the terms and conds page in the language the user prefers like Microsoft (they have this en-US prefix in their URL).
I managed to create separate HTML folders in my wwwroot like terms.en-US.html and terms.fr-CA etc.
I also created a controller named FilesController and it looks like this:
public class FilesController : Controller
{
[Route("Files/{language}/Terms")]
public IActionResult Terms(string language)
{
ViewData["lang"] = language;
return View();
}
}
And this is the Terms.cshtml file (so far):
#{
Layout= "_HomeLayout";
}
#Html.Raw(System.IO.File.ReadAllText(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(),"../files/documents/terms_and_conditions/" + #ViewData["lang"] + ".html")));
But obviously it doesnt work. How can I manage this?
PS: the only reason I am trying to add html into cshtml file is to benefit from the layout feature. Otherwise I would have directly return the html file in the controller like this:
public IActionResult Terms()
{
return File("~/files/documents/terms_and_conditions/tr-TR.html", "text/html");
}
I use File.ReadAllText to read the path directly and it works fine.
Below is my test code:
View:
#Html.Raw(File.ReadAllText("./wwwroot/files/"+#ViewData["lang"]+".html"))
Controller:
public IActionResult Index(string language)
{
ViewData["lang"] = language;
return View();
}
Test Result:
Is this result what you want?

Spring boot modify model.atrribute value defined in one controller from another controller

I have the following controller that renders an HTML view. Inside this controller, I have defined a model.attribute("bill", bill); , which renders the default value of 0 on the view. The controller looks like this:
#RequestMapping(value = "/products", method = RequestMethod.GET)
public String index(Model model, Product product) {
//not relevant code above
String bill = "0";
model.addAttribute("bill", bill);
I have another controller in different class that I want to update the value of bill and redirect me to the same page. My attempt to achieve this ended in producing this:
#RequestMapping(value="/products/checkout", method = RequestMethod.POST)
public String getBill(#RequestParam("checkout") String order, #RequestParam("bill") String bill, #ModelAttribute Model model) {
String finalBill = "124pounds";
model.addAttribute("bill", finalBill);
And the view looks like this:
<form th:action="#{/products/checkout}" method="post">
<h3> Please type your order:</h3>
<input type="text" th:name= "checkout" id="checkout" placeholder="banana,apple,tomato (separated with commas)">
<input type="submit" value="Checkout">
<h3>Your bill is :<span th:name="bill" th:text="' '+${bill}+' c'"></span></h3>
</form>
What I want to achieve is to make the second controller called getBill() to update the value of bill and redirect to the same page. I got lost a bit and I am not sure how to achieve the desired functionality.
Note: String bill = "0"; and String finalBill = "124pounds"; are just there to test if the value is changing when the Checkout button is pressed. The error I am getting looks like this.
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'bill' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'bill' is not present
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
What happens now is that the default 0 value is shown, but when I click the Checkout I get the error above. Basically I want to update the value from the getBill() and return the same view, which I am not sure is possible ?!
If I understand correctly, you are trying to only change the value o bill, and then return to the same html file, which is the one with the form. If that is correct, then all you need to do is remove the #ModelAttribute from getBill() and add the order string to the model.
it would look something like this:
#RequestMapping(value="/products/checkout", method = RequestMethod.POST)
public String getBill(#RequestParam("checkout") String order, #RequestParam("bill") String bill, Model model) {
String finalBill = "124pounds";
model.addAttribute("bill", finalBill);
model.addAttribute("checkout", order);
return "yourview";

Pass ViewBag value to PartailView MVC

My ViewBag value return empty when passing through PartialView.
CONTROLLER
[HttpGet]
public ActionResult Name()
{
ViewBag.Name = "Bob";
return PartialView();
}
View for above Name.cshtml
#{
<p>Name is: #ViewBag.Name </p>
}
Parent view Index.cshtml
#Html.Partial("Name")
When render it shows Name is: (blank) instead of Name is: Bob. I am still fairly new with MVC. Thank you for your help.
Please close this thread. I used #Html.Action("action","controller") and it solved my problem. Thank you.

ActionLink doesn't work

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)

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?