I have a Razor view in which I want to render the result of another action. So what I tried doing is this
#Html.Action("Index", "Home", new { area = "Portal" })
However this doesn't seem to render anything on the page. But when I check which URL is rendered by the Url.Action with the same parameters it's giving me the proper URL.
#Url.Action("Index", "Home", new { area = "Portal" }) // this shows /Portal/Blog/Index
#Html.Action("Index", "Home", new { area = "Portal" }) // this doesn't show anything
And if I go in my browser to /Portal/Blog/Index I can see content I'm trying to load just fine. I've even tried removing all of the code from HomeController so the action is simply
public ActionResult Index()
{
// also tried returning this.PartialView() but it makes no difference
return this.View();
}
and the Index.cshtml is just
#{
Layout = null;
}
<div>test</div>
Related
I want to show a success message after calling the following ajax.beginform
from Index view
#using (Ajax.BeginForm("Insert", "Home", new AjaxOptions() { UpdateTargetId = "result", HttpMethod = "POST" }))
{
#Html.TextAreaFor(m => m.openion)
}
this is my result div
<div id="result">
</div>
and my controller is
[Httppost]
public ActionResult InforMessage(openionModel usr)
{
return Content("Thanks for adding your openion");
}
but when i try this it is going to another view InforMessage
It is not updating the result div.
There is no Informessage Exist. Still it open a new page with message
"Thanks for adding your openion".How to solve this?
If your redirecting to another page its because you do not have the correct scripts loaded (or have duplicates or have them in the wrong order) so its doing a normal submit.
Ensure you have included (in order)
jquery-{version}.js
jquery.unobtrusive-ajax.js
I am using `#Html.Textbox("searchString") in Razor view page. I need this value of textbox in
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = "Value of textbox"}).
Of course the search string part in html action link is not working right now but i need this as i have specific route which works according to search string.
How do i pass value of textbox to action link?
i check this this,this,this and this.
What i tried is
<script type = "text/javascript">
var value = document.getElementbyID("searchString").Text;
var link = #Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = -1});
link.replace(-1,value);
</script>
Still no luck. I understand Razor renders at server side.
UPDATE
i have following textbox on the top of view:
#using (Html.BeginForm("Index", "trans_junction", FormMethod.Get))
{
<p>
Request No: #Html.TextBox("searchString")
<span><input type="submit" value="Search Request" /></span>
</p>
}
This textbox is search box in which user can search items.
there is an Action link as follows:
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id }) |
and a route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{searchString}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, searchString= UrlParameter.Optional }
);
}
}
Now i need to pass the values as my route map via actionlink. As suggested in answer by StephenMuecke, i tried to modify my #using (Html.BeginForm("Index", "trans_junction", FormMethod.Get)) with #using (Html.BeginForm("Index", "trans_junction", new { id = item.transaction_id }, FormMethod.Get))
but item is not accessible there.
When user click search button, url is http://localhost:57286/trans_junction/Index?searchString=20
if user click on Action link url is http://localhost:57286/trans_junction/Index/88
but i actually need is http://localhost:57286/trans_junction/Index/88/20
which preserve the the result of search and also pass the id.
I am adding screenshots for better understanding.
This is index view without search.
This is search result with searchString = 10.
This is after clicking the action link i.e. View Items, Here search results are not preserved.
Rather than manually trying to manipulate a link using javascript, use a form with method="get". Inside your loop
#using (Html.BeginForm("Index", "trans_junction", new { id = item.transaction_id }, FormMethod.Get))
{
#Html.TextBox("SearchString")
<button type="submit">View Items"</button> // style as a link if desired
}
which will make a GET call to
[HttpGet]
public ActionResult Index(int id, string searchString)
which assumes you have a specific route definition with
url: "trans_junction/Index/{id}/{searchstring}",
defaults: new { controller = "trans_junction", action = "Index" }
Edit (based on updated question details)
When your returning the filtered results, you will also need to pass back the value of searchString to the view so that in can be used to generate the route value in the ActionLink() methods, for example
ViewBag.Filter = searchString;
return View(....);
and then modify the links to
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = ViewBag.Filter })
You need to set the value on an event such as clicking on the ActionLink otherwise how do you know the value of the searchString textbox to replace in the Actionlink. Add this javascript on your page.
$(function(){
$("#myLink").click(function(){
var link = $(this).attr("href");
link.replace(-1, $(#searchString).val());
var link = $(this).attr("href", link);
});
});
And you Razor view actionlink needs to be
#Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = "-1"})
Try:
#{
var value = Request.Form["inputID"];
}
p.s. why aren't you using a form in stead of the link and submit the form when someone enters a searchString?
whoever downvoted this answer you could argument why or come up with a better solution? because in his case, searchString = Request.Form["inputID"]; should do what he is asking for.
I am struggling to get my code work, but I think I've read enough to suggest this is the correct way to approach this.
On my intranet, I'd like the user to type in a single word to search into a textbox, and check a checkbox. When the new page loads, I'd like the URL rewritting services of ASP.NET MVC to kick in and change a value from
mysite.com/?id=blah&isChecked=true
to
mysite.com/home/index/blah/true
My code isn't working in the sense of it gives no error, but doesn't do what I am explaining. So, I've removed the check box to just focus on the textbox.
My only route is
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{MyType}",
defaults: new { controller = "Home", action = "Index", MyType = UrlParameter.Optional }
);
My Controller
public ActionResult Index()
{
ViewBag.Message = "Modify this";
return View();
}
[HttpGet]
public ActionResult Index(string MyType)
{
ViewBag.Message = "..." + MyType;
return View();
}
and my View has
#using (Html.BeginForm("Index", "Home",FormMethod.Get))
{
<input name="MyType" /><br />
<input type="submit" />
}
#Html.ActionLink("Click me", "Index", new { #MyType = "Blah" }) //renders correctly
The problem is, it shows the querystring still in the address bar
mysite.com/?MyType=MySearchValue
instead of
mysite.com/Home/Index/MySearchValue
You can't do this purely with routing because the browser will always send form values as query string parameters when they are part of a GET request. Once the request has been sent to the server, the MVC framework can't do anything about the URL that was used.
This leaves you with only one real option (assuming you don't want to send a custom request using JavaScript), which is to explicitly redirect to the desired URL (meaning you will always have two requests when this form is submitted).
The simplest way of doing this is simply in the controller (rather, in a separate controller to ensure that there is no conflict in method signatures):
public class FormController : Controller
{
public ActionResult Index(string MyType)
{
return RedirectToAction("Index", "MyProperController", new { MyType });
}
}
If you direct your form to this controller action, MVC will then use the routing engine to generate the proper URL for the real action and redirect the browser accordingly.
You could do this from the same controller action but it would involve inspecting the request URL to check whether a query string was used or not and redirecting back to the same action, which is a little odd.
I have a single controller and view working that calls a web service, and returns a result. At the moment, it's my default controller, called Home, and it uses the Index view page.
It's working. I can post data and then put something on the refreshed screen. It reloads the same view.
Now, once I submit, and I get a good reply, I want to load a different controller/view.
My routes look like this right now:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home",
"{lang}",
new { controller = "Home", action = "Index", lang="English" });
routes.MapRoute(
"Location",
"{lang}",
new { controller = "Location", action = "Index", lang = "English" });
I created a controlled called Location, and it just has this:
//LocationController
public class LocationController : Controller
{
public ActionResult Index()
{
return View();
}
}
In my home controller, I am doing the logic, and then attempting to load the new page.
[HttpPost]
public ActionResult Index(HomeModel model)
{
var proxy = new Proxy();
var r = proxy.GetLocationByAddress(model.SearchString, o.ToString());
if(r==null)
{
ViewBag.Error = "Error during search";
return View(model);
}
ViewBag.Error = string.Format("Found {0} at {1}, {2}", r.StreetName, r.Latitude, r.Longitude);
return RedirectToAction("Index", "Location");
}
But when I run it, submit it, step through, it hits the RedirectToAction - but ... the Home screen simply refreshes. I never see the new Location view. What am I doing wrong here? I have't grasped Routes yet... I need to pass a new object to the Location.Index screen to display...
Your route mapping is incorrect, check this out: http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs
routes.MapRoute(
"Location",
"Location/{lang}",
new { controller = "Location", action = "Index", lang = "English" });
I don't think so you need to make any changes. As in your case you want to load different controller with its respecting view you need below change only
replace this code return RedirectToAction("Index", "Location");
with this code return Redirect("http://www.yoursite.com/Location/Index");
Your change is like redirection from one page to another therefore you need to put your complete path here
please try & reply if any problem
I've been looking for a long time for this but I'm still stuck, I need to have an upload control where the user can upload a document and give additional information.
I've had to do this before without the upload control so what I do is I get an ajax.beginform that will give all the input from the user to the controller and than close the popup trough a onsucces function, so this looks like this:
view:
#using (Ajax.BeginForm("Save", "Documents", new AjaxOptions { HttpMethod = "Post", OnSuccess = "CloseDialog" }, new { #class = "form-inline", id = "FormId" }))
{
#Html.Label("Description", "Description")
<div class="span3">
#Html.TextBoxFor(m => m.Description)
</div>
}
I tried adding there an Html.BeginForm but then I found out that it is not possible to use nested forms so I deleted this.
In my controller I have:
public PartialViewResult Index(string description)
{
var model = new DocumentsModel{ Description = description};
return PartialView(model);
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file, string description)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(#"D:\Documentds\"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index", new { description = description });
}
Ofcourse because the html.beginform won't work this controlleraction won't work either
So my question is how to do this without having to use a html.beginform?
You need to have the file upload inside the form and also the enctype="multipart/form-data" property on the form that calls uploadfile. That could be one problem.
Also, you could use JavaScript to submit the form you want from another part of the page without having them nested and keeping your design.