URL.action goes to server , but not the root URL - c#

Newbie to MVC, please excuse me if my question is not clear.
My view - https://abc.somecompany.org/ has the URL (being generated in a home controller )
#Url.Action("Index", "ContName" ,
new { id = viewModel.Id }, Request.Url.Scheme);
When I deploy it to the dev server, instead of showing the URL as
https://abc.somecompany.org/ContName/
or
https://abc.somecompany.org/ContName/Index
It is being changed to https://abc-server-8088/ContName, which obviously does not work outside the organization .
Why is the root URL being changed from abc.somecompany.org/ to abc-server-8088? Similar issue in both dev and test. This is being changed to something else
Do not want to change it to URL Content , because i have action and controller
viewModel.URLLINK = Url.Action(Etion.Index, Entroller.ContName,
new { id = viewModel.Id }, Request.Url.Scheme);
Want the same root URL (~) to show up in the emails

Try this easy solution:
#{
var myLink = $"{Request.Url.Scheme}://{Request.Url.Host}{#Url.Action("actionName", "controllerName", new { id = #Model.id })}";
Link
}
A short Review:
Html.ActionLink generates an tag. Forexample:
#Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123", foo=5 }, new { #class = "btn btn-primary" })
generates:
link text
Url.Action returns only a url. Forexmple, Url.Action("someaction", "somecontroller", new { id = "123" }) generates:
/somecontroller/someaction/123
But, the nice point about Url.action is that you can combine it with anchor tag to create the link content on the fly. For instance:
<a href="#Url.Action("actionName", "controllerName", new { id = #Model.id })">
<img src="#Model.src" />
</a>

Related

Routing without query string

I have added the following route before the default route
routes.MapRoute(
name: "RecordDefault",
url: "{controller}/{action}/{name}",
defaults: new { controller = "Person", action = "Record" }
);
I can hit the page I want using: sitename/Person/Record/John
But I have an global search in the navigation with the following code
#using (Html.BeginForm("Record", "Person", FormMethod.Get, new { #class = "navbar-form navbar-left" }))
{
#Html.TextBox("name", "", new { #class = "form-control", placeholder = "Search Name" })
}
When I submit the form the following URL is displayed: sitename/Person/Record?name=John
What do I have to do to ensure the URL is formatted without the query string parameter?
Thanks
Not the same as the posted duplicate, that marked answer does not resolve my problem and according to the comments it also didnt work for others.
Your form generates ../Person/Record?name=John because a browser has no knowledge of your routes (which is c# code running on your server). And the HTML standards require that the value of successful form controls be added as query string values when the method is GET.
In order to generate your preferred url (../Person/Record/John), you need javascript to intercept and cancel the default submit, and build a url to navigate to. Using jQuery:
$('form').submit(function() {
var baseUrl = $(this).attr('action');
// or var baseUrl = '#Url.Action("Record", "Person")';
var url = baseUrl + '/' + $('#name').val();
location.href = url; // redirect
return false; // cancel the default submit
});
Use form post FormMethod.Post instead of Get. So the value will be not appeared in querystring.
#using (Html.BeginForm("Record", "Person", FormMethod.Post, new { #class = "navbar-form navbar-left" }))
{
#Html.TextBox("name", "", new { #class = "form-control", placeholder = "Search Name" })
}
In your Controller add the following -
[HttpPost]
public ActionResult Record(string name)
{
//code for what needs to be performed.
return View();
}
In your view add the following code replacing your existing and check -
#using (Html.BeginForm("Record", "Person", FormMethod.Post))
{
#Html.TextBox("name")
<input type="submit" />
}

use a jsrender tag to supply routevalue in #Url.Action()

I'm working on an MVC project in which jsrender is used.
This is my first time working with jsrender (in fact I'm fairly new at javascript and C# too lol) and I've been struggling with one particular problem for a full day now.
I have the following javascript
$.post('#Url.Action("GetDocs","Place", new { placeID = Model.PlaceId})').done(
function (data) {
var template = $.templates("#doc-tmpl");
var htmlOut = template.render(data.documents);
$("#documentListContainer").append(htmlOut);
$(".docCount").html(data.count);
});
This gets all the data I need for the template below, but I need to create an Url.Action() using a piece of that data.
<script id="doc-tmpl" type="text/x-jsrender">
<div class="col-md-4">
<h5>{{:Name}}{{:test}}</h5>
<p id="DocId" class="hidden"><br />{{:DocId}}</p>
<img src="data:image;base64,{{:FrontCoverImg}}" width="140" height="230" />
Link
</div>
I need to supply the docId from the data in the routeValues of the #Url.Action("DisplayPDF","Place", new { docId = "{{:docId}}" }).
Obviously this isn't working in it's current state.
I've looked at the jsrender documentation and other Q&A to do with jsrender and MVC but I'm having trouble wrapping my head around the way it works.
one thing I have thought of is to create the #Url.Action() within the javascript and use a tag to pop it in the template, however I haven't been able to figure out how to add to the data from the $.post in order to make a tag available for it.
Edit:
What I mean from the above paragraph is, the data returned by the javascript/getDocs post is something like:
documents": [
{
"DocId": "86f86a32-5005-456c-8dd1-c023a66dd794",
"Name": "How to...",
"FrontCoverImg": "Base64String(docImg)"
},
{
"DocId": "d29f8afc-3191-47f1-9b88-1de08582ba27",
"Name": "A Document",
"FrontCoverImg": "Base64String(docImg)"
}
],
"count": ​2
}
Which is then set up to fill in the template. I'm hoping there is a way to add the #Url.Action() statement to those key/value pairs, something like:
"viewdoc" : '##Url.Action("DisplayPDF", "Place", new {DocId = ' + DocId + ', ##class = "btn btn-default" })';
(not sure if the syntax is quite right there) so I could then put {{:viewdoc}} into the template.
Am I at least on the right track? lol
try this ,
var id = $('#docId').val();
var link = '#URL.Action("download file", "download", new { id = "-1" })';
link = link.replace("-1", id);
Source : How to access javascript variable within #URL.Action()
Ok so after leaving it alone for a week then much experimentation and googling, I found my solution.
I've created the link in the controller, where the JSON data is set.
I had to request the leftmost part of the URL and hardcode the controller/action part of the url, otherwise it crammed the new url on the end of the current page url.
So the solution is as follows:
The Controller:
foreach (Doc document in docs)
{
DocJson dj = new DocJson();
dj.DocId = document.DocId;
dj.Name = document.Comments;
//get base Url
var request = HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);
dj.docLink = request + "/Place/DisplayPDF?DocId=" + document.DocId;
//get image bytes
var docImg = document.FrontCoverImg;
dj.FrontCoverImg = Convert.ToBase64String(docImg);
documents.Add(dj);
}
return Json(new { documents = documents, count = documents.Count() }, JsonRequestBehavior.AllowGet);
(in the view)
The Javascript getting the data:
//getDocs
$.post('#Url.Action("GetDocs","Place", new { placeID = Model.PlaceId})').done(
function (data) {
console.log(data);
var template = $.templates("#doc-tmpl");
var htmlOut = template.render(data.documents);
$("#documentListContainer").append(htmlOut);
$(".docCount").html(data.count);
});
(in the view)
And the template itself:
#* Document jsrender template *#
<script id="doc-tmpl" type="text/x-jsrender">
<div class="col-md-4">
<a href="{{:docLink}}" target="_blank">
<h5>{{:Name}}</h5>
<p id="DocId" class="hidden"><br />{{:DocId}}</p>
<img src="data:image;base64,{{:FrontCoverImg}}" width="140" height="230" />
</a>
</div>
</script>

Send DropDownList Value as parameter to ActionLink

I am trying to use #Html.ActionLink and send the value of my #Html.DropDownList selected item.
here is my code:
<span class="MemberList">
#Html.DropDownList("ParticipantList", new SelectList(ViewBag.ParticipantList, "UserName", "UserName", ViewBag.ParticipantList), new { #class = "members" })
</span>
<span>
#Html.ActionLink("Login", "Impersonate", "Studio", new { username = DropDown.SelectedValue }, new { #class = "gobutton3" })
</span>
So I am wondering how could I send the value to the ActionLink
the only way to add dynamic content to a link is through script
<a class="lnkLogin" href="#">Login</a>
and then in your script
$('.lnkLogin').on('click', function(){
var url = '#Url.Action("Impersonate", "Studio", new { username = "----" })';
url = url.replace("----", $('#ParticipantList').val());
window.location = url;
});
this will redirect using the window.location. being a login you may want to do an ajax call to verify credentials before redirecting.

MVC5 Url.Action showing RouteValues as QueryStrings

I am trying to have a custom route that use route values rather than query string, not sure why they are showing up as only query strings from a url action
Here is my route setup from my AreaRegistration
context.MapRoute(
"Member_Bank_Account",
"Member/{controller}/{bank}/{account}",
new { action = "Index" },
new[] { "Application.Web.Areas.Member.Controllers" });
And when I call it from html
<a href="#Url.Action("Index",
"Bank",
new {area = "Member", bank = "MyBank", account = "Primary"})"
class="btn btn-primary btn-sm">Primary</a>
Both urls seems to work fine..
I can go to:
http://localhost/Member/Bank/MyBank/Primary
http://localhost/Member/Bank?bank=MyBank&account=Primary
But the html link always shows query string, not sure what i am doing wrong.
Any idea how to get it to show as a route instead of having query strings?

Routing Issue on asp.net mvc 5 GET

I am trying to get my product search URL to look like "Products/Search/{search term here}".
I am using attribute based routing and my controller action looks like this:
[HttpGet]
[Route("Products/Search/{searchTerm?}", Name="ProductSearch")]
public ActionResult Search(string searchTerm = "")
{
return View();
}
I have tried using the HTML Helper for BeginForm and BeginRouteForm (shown below) but have not had luck with either. The right action is being called, but my URL looks like "Products/Search?searchTerm"
BeginRouteForm
#using (Html.BeginRouteForm("ProductSearch", new { searchTerm = "" }, FormMethod.Get, new { Class = "navbar-form navbar-right", role = "search" }))
{
<div class="form-group">
#Html.TextBox("searchTerm", null, new { Class = "form-control", placeholder = "Item # or Name" })
</div>
<button type="submit" class="btn btn-default">Search</button>
}
BeginForm
#using (Html.BeginForm("Search", "Products", new { searchTerm = "" }, FormMethod.Get, new { Class = "navbar-form navbar-right", role = "search" }))
{
<div class="form-group">
#Html.TextBox("searchTerm", null, new { Class = "form-control", placeholder = "Item # or Name" })
</div>
<button type="submit" class="btn btn-default">Search</button>
}
I have gone through debugging and the right route is selected, the URL is just not displaying how I wanted it to. What am I missing?
Here is the solution I suggest -
You have the following controller Action -
[HttpGet]
public ActionResult Search(string searchTerm = "")
{
return View();
}
Let the view be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
var name = $("#search").val();
var url = '#Url.Action("Search", "Action")' + '/' + name;
window.location.href = url;
});
});
</script>
<input type="text" name="searchText" id="search"/>
<input type="button" value="click" id="click"/>
And when you click the button -
Do not forget to have proper route to be added on to the route configuration -
routes.MapRoute(
name: "searchaction",
url: "{controller}/{action}/{searchTerm}",
defaults: new { controller = "Action", action = "Search" }
);
The problem you think you are experiencing isn't because of anything about ASP.Net MVC. All Html Forms that use the method GET will translate all input elements into QueryString parameters. This is just a W3C standard.
If you want this to work, you'll have to write jQuery to throw an event before the form is submitted, take the text value from the input store it temporarily, empty the input box, and then update the action by appending the temporary value.
I don't think that BeginRouteForm works the way that you're expecting it to. According to the documentation, all that the method does is insert a <form> using the arguments provided. If you had provided something other than an empty string for the route value such as , new { searchTerm = "somesearchterm" }, you would see that show up in the Url as "/product/search/somesearchterm". As it is now, however, the form will be processed as normal, putting the search term on the Url as a normal query parameter.

Categories

Resources