Specify Action on sub-controller when using Html.RenderAction - asp.net-mvc

I have a UserControl that I call with Html.RenderAction(...), so far so good..
Then I want to specify in the user control, which action should be used
Html.BeginForm("DeleteComment", "Comments", new { Id = "frmDelete" }, FormMethod.Post);%>
<%= Html.SubmitImage( "imgbtnDelete", "/image.png", new { ... })%>
<% Html.EndForm(); %>
And therein lies my problem; this calls the user control's controller/action.
What I want to happen is to call the pages action first and then be able to specify what action to call on the user control's controller.
Is this possible??
Thanks from an MVC noob

A simple solution would be to set the action of the form to be /{sub-controller}/{action-method}
Something like
Html.BeginForm("DeleteComment", "Comments", new { Id = "frmDelete", action="/{sub-controller}/{action-method}" }, FormMethod.Post);%>
HTH,
Dan

Related

2 different routes on one page?

Hi I'm pretty new with MVC2 or MVC in general. If it's one thing I get caught up with it's routes. Like now I got this scenario. Im going from the regular site to Admin. My navigation is the same partialview on both I just do a check which data to render something like this.
<% if (!Request.RawUrl.Contains("Admin")){%>
<% foreach (var site in Model) { %>
<%= Html.MenuItem(site.BelongSite, "Sida", "Site", site.BelongSite) %> |
<%} %>
<%} else {%>
<%= Html.ActionLink("Konfig", "Konfigurera", "Admin") %>
<% } %>
My route looks like this
routes.MapRoute(
"Admin", // Route name
"Admin/{action}/{name}", // URL with parameters
new { controller = "Admin", action = "konfigurera", name = UrlParameter.Optional } // Parameter defaults
);
On my View called Konfigurera I got Edit sites and they use the route above and it works great. The navigation tho dont get no action assigned to it. It's just <a href='Admin/'>
The navigation is in the shared folder, and it is a strongly typed. Any Ideas? I been struggling with this for about a hour now
Thanks for any input
EDIT
this is just one of those omg I'm so stupid moments. Ofcause the the link gone be only <a href='Admin/' because it's the default link (as the default values of the route). I noticed this as I put more links to the Admin navigation and they was ok. Well hope this can help anybody in the same situation as I had.
I wonder how I should do if I come up with the solution myself?
Ofcause the the link gone be only <a href='Admin/' because it's the default link (as the default values of the route). So really no problem here Index always gone result in a "empty" link.

Asp.Net Mvc 2 - RenderAction List with a create

First, I use Asp.Net MVC 2 RC 2.
What I want to do is to list a comment view and below this view being able to add comment (with validations). For example, something like when you add comment in stackoverflow. Except that my page should work with or without javascript enabled.
So to solve that problem I use the new RenderAction and it partially solved my problem. I got my list view that calls my addcomment usercontrol with RenderAction.
The validations work. My problem occurs when I try to add a comment that it's valid. The page didn't refresh correctly. If I got in the database, my comment is added, but it's doesn't have been refresh in my list view and the add comment form isn't clear.
I think it's because of how the workflow is rendered.
Maybe if someone got a example or blog about this, it's can help me to get it right...
At the bottom of my Comment/List.aspx
<% Html.RenderAction("Create", "Comment"); %>
In Comment/Create.ascx
<% using (Html.BeginForm(
ViewContext.ParentActionViewContext.RouteData
.Values["action"].ToString(),
ViewContext.ParentActionViewContext.RouteData
.Values["controller"].ToString(),
FormMethod.Post, new { id = "createForm" })){ %>
You can force the parent View to refresh itself with a small hack involving ViewContext.ParentActionViewContext.
In your CommentController class:
public ActionResult Create(Comment comment)
{
...
if (isValid) // Comment entered in form is valid
{
ControllerContext.ParentActionViewContext.ViewData["SuccessfullCreate"] = true;
}
...
}
And in your Comment/List.aspx page (view) :
<% Html.RenderAction("Create", "Comment"); %>
<%
if (ViewContext.ViewData["SuccessfulCreate"] != null)
{
string action = ViewContext.RouteData.Values["action"].ToString();
string controller = ViewContext.RouteData.Values["controller"].ToString();
string url = "/" + controller + "/" + action;
Response.Redirect(url);
}
%>
So basically, what's happening is that the child action is "telling" the parent action to refresh itself by using the parent's ViewData.
It's kind of a hack, but it works fine for what's you're doing.

asp.net mvc parameter from page to a partial view

I'm with a problem, I have a ajax link that pass a parameter, but, the page that it opens does not need that parameter. The page only load 2 partial views, one of those need that parameter passed to the page to load the data correctly, and the other just need to load a form, so, don't need that parameter. How can i acheive this?
In order to do what you want, you will need to add the id to the ViewData construct.
var sysfunctions= UnisegurancaService.FunctionsRepository.All();
ViewData["NeededID"] = id
return View(sysfunctions);
then in your view where you render the partial
<%= Html.RenderPartial("GridFunction", (int)ViewData["NeededID"]) %>
Cast as required of course.
Whatever gets pushed in as the second param becomes the .Model in the partial. I would suggest also strongly typing your partials.
Try this:
<% Html.RenderPartial("GridFunction", new ViewDataDictionary {{"Id", ViewData["Id"]}}); %>
UPDATED:
And add this in your controller action:
ViewData["Id"] = Id;
UPDATED:
And in your GridFunction partial View you can access Id as:
<%= ViewData["Id"] %>
//Controller
public ActionResult EditFunctions(int id)
{
var sysfunctions= UnisegurancaService.FunctionsRepository.All();
return View(sysfunctions);
}
// This is the controller (it does no need the parameter "ID")
//This is the view "EditFunctions"
<div id="formFunction">
<% Html.RenderPartial("FormFunction"); %>
</div>
<div id="gridFunction">
<% Html.RenderPartial("GridFunction"); %> // The grid needs the ID to work correctly but its in the parent page not in the partial call....and the call is an ajax call
</div>
If some dependency of the page needs the parameter, then the page needs to know enough to pass the data in, so the page should be able to provide the data. Or, more simply, just add the parameter to the Page's viewdata and be done with it.

Asp.Net MVC Call another controller from view

Let say I'm on the page "Home/Index" and I want to go to the page MyOtherController/Index/1
How can I do this ?
I try :
<%= Html.ActionLink("Test", "Index", "MyOtherController", new { id=item.Id }) %>
Did I also have to add a route in Global.aspx file ?
One option is to specify the name of the controller in the list of routevalues:
<%= Html.ActionLink("Test", "Index"
, new { controller = "MyOtherController", id = item.Id }) %>
An alternative is to use the overload of ActionLink with htmlAttributes = null:
<%= Html.ActionLink("Test", "Index"
, "MyOtherController", new { id = item.Id }, null) %>
The default route in the ASP.NET MVC template takes care of the routing in this case.
I don't believe ActionLink has an overload matching that particular signature. You would need to add "null" after your route values to find a matching one (for htmlAttributes). Ole's solution would be cleaner though so it's really a matter of preference. It also will help with readability so you don't have to guess whether each parameter is link text, an action/controller, etc.

How to prevent auto filling posted values in asp.net mvc ajax form

Inside of an asp.net mvc partial view, I have an Ajax form that posts a value and replaces the contents of its parent container with another instance of the form.
Index.aspx view:
<div id="tags">
<% Html.RenderPartial("Tags", Model); %>
</div>
Tags.ascx partial view:
<% using(Ajax.BeginForm("tag", new AjaxOptions { UpdateTargetId = "tags" }))
{ %>
Add tag: <%= Html.TextBox("tagName")%>
<input type="submit" value="Add" />
<% } %>
The controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Tag(string tagName) {
// do stuff
return PartialView("Tags", ...);
}
The problem is when the new instance of the form returns, the posted value is already stored in the input field. As in, whatever I posted as the 'tagName' will stay in the textbox. Firebug shows that the value is hardcoded in the response.
Is there any way to clear the input textbox's value when returning the partial view?
I've tried:
<%= Html.TextBox("tagName", string.Empty)%>
and
<%= Html.TextBox("tagName", string.Empty, new { value = "" })%>`
neither of which do anything.
EDIT:
I realize there are js solutions, which I may end up having to use, but I was wondering if there were any ways of doing it in the backend?
I'm not sure if this solution is "good enough" for you, but couldn't you just empty the form in a JS callback function from your ajax call? If you're using jQuery on your site, the callback function could look something like this:
function emptyFormOnReturn() {
$(':input').val();
}
I am not entirely sure if it will, but in case the above code also removes the text on your submit button, change the selector to ':input[type!=submit]'.
yes you should use jquery to set values on response
if you change your code to use jquery for ajax operations, you can call you settingvalues function on success callback...example:
http://docs.jquery.com/Ajax/jQuery.ajax#options

Resources