Search Results

Search found 56 results on 3 pages for 'renderaction'.

Page 1/3 | 1 2 3  | Next Page >

  • Html.RenderAction Failed when Validation Failed

    - by Shaun
    RenderAction method had been introduced when ASP.NET MVC 1.0 released in its MvcFuture assembly and then final announced along with the ASP.NET MVC 2.0. Similar as RenderPartial, the RenderAction can display some HTML markups which defined in a partial view in any parent views. But the RenderAction gives us the ability to populate the data from an action which may different from the action which populating the main view. For example, in Home/Index.aspx we can invoke the Html.RenderPartial(“MyPartialView”) but the data of MyPartialView must be populated by the Index action of the Home controller. If we need the MyPartialView to be shown in Product/Create.aspx we have to copy (or invoke) the relevant code from the Index action in Home controller to the Create action in the Product controller which is painful. But if we are using Html.RenderAction we can tell the ASP.NET MVC from which action/controller the data should be populated. in that way in the Home/Index.aspx and Product/Create.aspx views we just need to call Html.RenderAction(“CreateMyPartialView”, “MyPartialView”) so it will invoke the CreateMyPartialView action in MyPartialView controller regardless from which main view. But in my current project we found a bug when I implement a RenderAction method in the master page to show something that need to connect to the backend data center when the validation logic was failed on some pages. I created a sample application below.   Demo application I created an ASP.NET MVC 2 application and here I need to display the current date and time on the master page. I created an action in the Home controller named TimeSlot and stored the current date into ViewDate. This method was marked as HttpGet as it just retrieves some data instead of changing anything. 1: [HttpGet] 2: public ActionResult TimeSlot() 3: { 4: ViewData["timeslot"] = DateTime.Now; 5: return View("TimeSlot"); 6: } Next, I created a partial view under the Shared folder to display the date and time string. 1: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %> 2:  3: <span>Now: <% 1: : ViewData["timeslot"].ToString() %></span> Then at the master page I used Html.RenderAction to display it in front of the logon link. 1: <div id="logindisplay"> 2: <% 1: Html.RenderAction("TimeSlot", "Home"); %> 3:  4: <% 1: Html.RenderPartial("LogOnUserControl"); %> 5: </div> It’s fairly simple and works well when I navigated to any pages. But when I moved to the logon page and click the LogOn button without input anything in username and password the validation failed and my website crashed with the beautiful yellow page. (I really like its color style and fonts…)   How ASP.NET MVC executes Html.RenderAction In this example all other pages were rendered successful which means the ASP.NET MVC found the TimeSolt action under the Home controller except this situation. The only different is that when I clicked the LogOn button the browser send an HttpPost request to the server. Is that the reason of this bug? I created another action in Home controller with the same action name but for HttpPost. 1: [HttpPost] 2: [ActionName("TimeSlot")] 3: public ActionResult TimeSlot(object dummy) 4: { 5: return TimeSlot(); 6: } Or, I can use the AcceptVerbsAttribute on the TimeSlot action to let it allow both HttpGet and HttpPost. 1: [AcceptVerbs("GET", "POST")] 2: public ActionResult TimeSlot() 3: { 4: ViewData["timeslot"] = DateTime.Now; 5: return View("TimeSlot"); 6: } And then repeat what I did before and this time it worked well. Why we need the action for HttpPost here as it’s just data retrieving? That is because of how ASP.NET MVC executes the RenderAction method. In the source code of ASP.NET MVC we can see when proforming the RenderAction ASP.NET MVC creates a RequestContext instance from the current RequestContext and created a ChildActionMvcHandler instance which inherits from MvcHandler class. Then the ASP.NET MVC processes the handler through the HttpContext.Server.Execute method. That means it performs the action as a stand-alone request asynchronously and flush the result into the  TextWriter which is being used to render the current page. Since when I clicked the LogOn the request was in HttpPost so when ASP.NET MVC processed the ChildActionMvcHandler it would find the action which allow the current request method, which is HttpPost. Then our TimeSlot method in HttpGet would not be matched.   Summary In this post I introduced a bug in my currently developing project regards the new Html.RenderAction method provided within ASP.NET MVC 2 when processing a HttpPost request. In ASP.NET MVC world the underlying Http information became more important than in ASP.NET WebForm world. We need to pay more attention on which kind of request it currently created and how ASP.NET MVC processes.   Hope this helps, Shaun   All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • Html.RenderAction<MyController> - does not have type parameters

    - by Ami
    Hi, I'm trying to use RenderAction in the following way: '<% Html.RenderAction( x = x.ControllerAction() ); %' as seen here: http://devlicio.us/blogs/derik_whittaker/archive/2008/11/24/renderpartial-vs-renderaction.aspx and here: http://eduncan911.com/blog/html-renderaction-for-asp-net-mvc-1-0.aspx but I keep getting an error about the method not having type parameters. also in MSDN I see there is no documentation for it, and also checking the MVC source code I can't find anything. I'm using the latest ASP.Net MVC (2.0 RTM) is this feature no longer available? how can I use it? thanks.

    Read the article

  • Like Html.RenderAction() but without reinstantiating the controller object

    - by Jørn Schou-Rode
    I like to use the RenderAction extension method on the HtmlHelper object to render sidebars and the like in pages, as it allows me to keep the data access code for each such part in separate methods on the controller. Using an abstract controller base, I can define a default "sidebar strategy", which can then be refined by overriding the method in a concrete controller, when needed. The only "problem" I have with this approach, is that the RenderAction is built in a way where it always creates a news instance of the controller class, even when rendering actions from the controller already in action. Some of my controllers does some data lookup in their Initialize method, and using the RenderAction method in the view causes this to occur several times in the same request. Is there some alternative to RenderAction which will reuse the controller object if the action method to be invoked is on the same controller class as the "parent" action?

    Read the article

  • RenderAction not finding action method in current controller in current area

    - by Andrew Davey
    I'm creating an ASP.NET MVC 2 (RTM) project that uses areas. The Index action of the Home controller of one area needs to use RenderAction to generate a sub-section of the page. The action called is also defined in the same Home controller. So the call should just be: <% Html.RenderAction("List") %> However, I get an exception: A public action method 'List' was not found on controller 'RareBridge.Web.Areas.Events.Controllers.HomeController'. Note that I'm not in the "Events" area! I'm in a completely different area. If I remove the "Events" home controller, then the exception still occurs but names a different controller (still not the one I want it to call). I've also tried providing the controller name and area to the RenderAction method, but the same exception occurs. What is going on here? BTW: I am using Autofac as my IoC container

    Read the article

  • MVC2 Client validation with Annotations in View with RenderAction

    - by Olle
    I'm having problem with client side validation on a View that renders a dropdownlist with help of a Html.RenderAction. I have two controllers. SpecieController and CatchController and I've created ViewModels for my views. I want to keep it as DRY as possible and I will most probably need a DropDownList for all Specie elsewhere in the near future. When I create a Catch i need to set a relationship to one specie, I do this with an id that I get from the DropDownList of Species. ViewModels.Catch.Create [Required] public int Length { get; set; } [Required] public int Weight { get; set; } [Required] [Range(1, int.MaxValue)] public int SpecieId { get; set; } ViewModels.Specie.List public DropDownList(IEnumerable<SelectListItem> species) { this.Species = species; } public IEnumerable<SelectListItem> Species { get; private set; } My View for the Catch.Create action uses the ViewModels.Catch.Create as a model. But it feels that I'm missing something in the implemetation. What I want in my head is to connect the selected value in the DropDownList that comes from the RenderAction to my SpecieId. View.Catch.Create <div class="editor-label"> <%: Html.LabelFor(model => model.SpecieId) %> </div> <div class="editor-field"> <%-- Before DRY refactoring, works like I want but not DRY <%: Html.DropDownListFor(model => model.SpecieId, Model.Species) %> --%> <% Html.RenderAction("DropDownList", "Specie"); %> <%: Html.ValidationMessageFor(model => model.SpecieId) %> </div> CatchController.Create [HttpPost] public ActionResult Create(ViewModels.CatchModels.Create myCatch) { if (ModelState.IsValid) { // Can we make this StronglyTyped? int specieId = int.Parse(Request["Species"]); // Save to db Catch newCatch = new Catch(); newCatch.Length = myCatch.Length; newCatch.Weight = myCatch.Weight; newCatch.Specie = SpecieService.GetById(specieId); newCatch.User = UserService.GetUserByUsername(User.Identity.Name); CatchService.Save(newCatch); } This scenario works but not as smooth as i want. ClientSide validation does not work for SpecieId (after i refactored), I see why but don't know how I can ix it. Can I "glue" the DropDownList SelectedValue into myCatch so I don't need to get the value from Request["Species"] Thanks in advance for taking your time on this.

    Read the article

  • Asp.Net MVC2 RenderAction changes page mime type?

    - by Gabe Moothart
    It appears that calling Html.RenderAction in Asp.Net MVC2 apps can alter the mime type of the page if the child action's type is different than the parent action's. The code below (testing in MVC2 RTM), which seems sensible to me, will return a result of type application/json when calling Home/Index. Instead of dispylaying the page, the browser will barf and ask you if you want to download it. My question: Am I missing something? Is this a bug? If so, what's the best workaround? controller: public class HomeController : Controller { public ActionResult Index() { ViewData[ "Message" ] = "Welcome to ASP.NET MVC!"; return View(); } [ChildActionOnly] public JsonResult States() { string[] states = new[] { "AK", "AL", "AR", "AZ", }; return Json(states, JsonRequestBehavior.AllowGet); } } view: <h2><%= Html.Encode(ViewData["Message"]) %></h2> <p> To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. </p> <script> var states = <% Html.RenderAction("States"); %>; </script>

    Read the article

  • Renderpartial or renderaction

    - by femi
    have an action that generates active vacancies. The code is below; public ViewResult OpenVacancies() { var openvacancies = db.GetActiveVacancies(); return View(openvacancies); } I want to use this list on several pages so i guess the best thing to use is html.renderaction (please correct me if i am wrong here). Please note that the view and .ascx control are in an Area. I then created a view by right clicking inside the action and create a .ascx and a strongly typed view of Vacancy. I chose a view content of "List". I then added this line to the required page; <% Html.RenderAction("OpenVacancies"); % Please note that the view and .ascx control are in an Area. The error i got is; The type or namespace name 'Vacancy' could not be found (are you missing a using directive or an assembly reference?) the .ascx code is below; <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" % <table> <tr> <th></th> <th> VacancyID </th> <th> JobTitle </th> <th> PositionID </th> <th> LocationID </th> <th> JobDescription </th> <th> JobConditions </th> <th> Qualifications </th> <th> RequiredSkills </th> <th> Certifications </th> <th> AdvertDate </th> <th> AdvertExpiryDate </th> <th> Status </th> <th> StaffLevel </th> <th> LineManagerEmail </th> <th> ApprovalFlag </th> <th> RequisitionDate </th> </tr> <% foreach (var item in Model) { %> <tr> <td> <%= Html.ActionLink("Edit", "Edit", new { id=item.VacancyID }) %> | <%= Html.ActionLink("Details", "Details", new { id=item.VacancyID })%> | <%= Html.ActionLink("Delete", "Delete", new { id=item.VacancyID })%> </td> <td> <%= Html.Encode(item.VacancyID) %> </td> <td> <%= Html.Encode(item.JobTitle) %> </td> <td> <%= Html.Encode(item.PositionID) %> </td> <td> <%= Html.Encode(item.LocationID) %> </td> <td> <%= Html.Encode(item.JobDescription) %> </td> <td> <%= Html.Encode(item.JobConditions) %> </td> <td> <%= Html.Encode(item.Qualifications) %> </td> <td> <%= Html.Encode(item.RequiredSkills) %> </td> <td> <%= Html.Encode(item.Certifications) %> </td> <td> <%= Html.Encode(String.Format("{0:g}", item.AdvertDate)) %> </td> <td> <%= Html.Encode(String.Format("{0:g}", item.AdvertExpiryDate)) %> </td> <td> <%= Html.Encode(item.Status) %> </td> <td> <%= Html.Encode(item.StaffLevel) %> </td> <td> <%= Html.Encode(item.LineManagerEmail) %> </td> <td> <%= Html.Encode(item.ApprovalFlag) %> </td> <td> <%= Html.Encode(String.Format("{0:g}", item.RequisitionDate)) %> </td> </tr> <% } %> </table> <p> <%= Html.ActionLink("Create New", "Create") %> </p>

    Read the article

  • SparkViewEngine, RenderAction and Areas with ASP MVC 2 Beta?!

    - by scooby37
    I just ran into trouble with the AreaDescriptionFilter of Spark using MVC 2 Beta. The following line is from my Application.spark file. It results in the view engine looking in all possible locations of the view - except in the folders of the area "Shell". # Html.RenderAction("ShowMainMenu", "Navigation", new { area = "Shell" }); Running the same action using http://localhost/Shell/Navigation/ShowMainMenu executes fine and recognizes the area's view directory as expected. Any ideas how to fix this?

    Read the article

  • RenderAction in an HtmlHelperExtension Method?

    - by TimLeung
    I am trying to call the RenderAction Extension Method within my own Html Helper: System.Web.Mvc.Html.ChildActionExtensions.RenderAction(helper, "account", "login"); this is so that along with some additional logic, I would like all html helpers to use a common method name structure when calling it on the view: <%= Html.CompanyName().RenderAccount() %> but the problem I am having is that, asp.net will complain about not finding the actual route it needs to process. It does not take in the parameters of "controller" to be used as the action and "login" to be used as the action. It seems to only reference the current route. Any ideas how I can package up the RenderAction?

    Read the article

  • Castle Windsor Controller Factory and RenderAction

    - by Bradley Landis
    I am running into an issue when using my Castle Windsor Controller Factory with the new RenderAction method. I get the following error message: A single instance of controller 'MyController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request. This is the code in my controller factory: public class CastleWindsorControllerFactory : DefaultControllerFactory { private IWindsorContainer container; public CastleWindsorControllerFactory(IWindsorContainer container) { this.container = container; } public override IController CreateController(RequestContext requestContext, string controllerName) { return container.Resolve(controllerName) as IController; } public override void ReleaseController(IController controller) { this.container.Release(controller); } } Does anyone know what changes I need to make to make it work with RenderAction? I also find the error message slightly strange because it talks about multiple requests, but from what I can tell RenderAction doesn't actually create another request (BeginRequest isn't fired again).

    Read the article

  • Html.RenderAction - the controller for path '/' was not found

    - by billyonemate
    Using ASP.NET MVC 2 and and Html.RenderAction in my masterpage implemented as below throws an error with "the controller for path '/' was not found": I'm a bit of a newbie, do i have to do something in RegisterRoutes to make this work? <% Html.RenderAction("TeaserList", "SportEventController"); %> public class SportEventController : Controller { public string TeaserList() { return "hi from teaserlist"; } }

    Read the article

  • MVC HTML.RenderAction – Error: Duration must be a positive number

    - by BarDev
    On my website I want the user to have the ability to login/logout from any page. When the user select login button a modal dialog will be present to the user for him to enter in his credentials. Since login will be on every page, I thought I would create a partial view for the login and add it to the layout page. But when I did this I got the following error: Exception Details: System.InvalidOperationException: Duration must be a positive number. There are other ways to work around this that would not using partial views, but I believe this should work. So to test this, I decided to make everything simple with the following code: Created a layout page with the following code @{Html.RenderAction("_Login", "Account");} In the AccountController: public ActionResult _Login() { return PartialView("_Login"); } Partial View _Login <a id="signin">Login</a> But when I run this simple version this I still get this error: Exception Details: System.InvalidOperationException: Duration must be a positive number. Source of error points to "@{Html.RenderAction("_Login", "Account");}" There are some conversations on the web that are similar to my problem, which identifies this as bug with MVC (see links below). But the links pertain to Caching, and I'm not doing any caching. OuputCache Cache Profile does not work for child actions http://aspnet.codeplex.com/workitem/7923 Asp.Net MVC 3 Partial Page Output Caching Not Honoring Config Settings Asp.Net MVC 3 Partial Page Output Caching Not Honoring Config Settings Caching ChildActions using cache profiles won't work? Caching ChildActions using cache profiles won't work? I'm not sure if this makes a difference, but I'll go ahead and add it here. I'm using MVC 3 with Razor. Update Stack Trace [InvalidOperationException: Duration must be a positive number.] System.Web.Mvc.OutputCacheAttribute.ValidateChildActionConfiguration() +624394 System.Web.Mvc.OutputCacheAttribute.OnActionExecuting(ActionExecutingContext filterContext) +127 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +72 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +784922 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters) +314 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976 System.Web.Mvc.Controller.ExecuteCore() +159 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335 System.Web.Mvc.<c_DisplayClassb.b_5() +62 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +20 System.Web.Mvc.<c_DisplayClasse.b_d() +54 System.Web.Mvc.<c_DisplayClass4.b_3() +15 System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +41 System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1363 [HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.] System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +2419 System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +275 System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +94 System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +838 System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +56 ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in c:\Projects\Odat Projects\Odat\Source\Presentation\Odat.PublicWebSite\Views\Shared\SiteLayout.cshtml:80 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +104 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +173 System.Web.WebPages.WebPageBase.Write(HelperResult result) +89 System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action1 body) +234 System.Web.WebPages.WebPageBase.PopContext() +234 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +384 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +33 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) +784900 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) +784900 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList1 filters, ActionResult actionResult) +265 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +784976 System.Web.Mvc.Controller.ExecuteCore() +159 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +335 System.Web.Mvc.<c_DisplayClassb.b_5() +62 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +20 System.Web.Mvc.<c_DisplayClasse.b_d() +54 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371 Update When I Break in Code, it errors at @{Html.RenderAction("_Login", "Account");} with the following exception. The inner exception Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'. at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) at System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) at ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in c:\Projects\Odat Projects\Odat\Source\Presentation\Odat.PublicWebSite\Views\Shared\SiteLayout.cshtml:line 80 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.WebPages.WebPageBase.Write(HelperResult result) at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action1 body) at System.Web.WebPages.WebPageBase.PopContext() at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) Answer Thanks Darin Dimitrov Come to find out, my AccountController had the following attribute [System.Web.Mvc.OutputCache(NoStore =true, Duration = 0, VaryByParam = "*")]. I don't believe this should caused a problem, but when I removed the attribute everything worked. BarDev

    Read the article

  • Specify Action on sub-controller when using Html.RenderAction

    - by iammaz
    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

    Read the article

  • Render action return View(); form problem

    - by Roger Rogers
    I'm new to MVC, so please bear with me. :-) I've got a strongly typed "Story" View. This View (story) can have Comments. I've created two Views (not partials) for my Comments controller "ListStoryComments" and "CreateStoryComment", which do what their names imply. These Views are included in the Story View using RenderAction, e.g.: <!-- List comments --> <h2>All Comments</h2> <% Html.RenderAction("ListStoryComments", "Comments", new { id = Model.Story.Id }); %> <!-- Create new comment --> <% Html.RenderAction("CreateStoryComment", "Comments", new { id = Model.Story.Id }); %> (I pass in the Story id in order to list related comments). All works as I hoped, except, when I post a new comment using the form, it returns the current (parent) View, but the Comments form field is still showing the last content I typed in and the ListStoryComments View isn’t updated to show the new story. Basically, the page is being loaded from cache, as if I had pressed the browser’s back button. If I press f5 it will try to repost the form. If I reload the page manually (reenter the URL in the browser's address bar), and then press f5, I will see my new content and the empty form field, which is my desired result. For completeness, my CreateStoryComment action looks like this: [HttpPost] public ActionResult CreateStoryComment([Bind(Exclude = "Id, Timestamp, ByUserId, ForUserId")]Comment commentToCreate) { try { commentToCreate.ByUserId = userGuid; commentToCreate.ForUserId = userGuid; commentToCreate.StoryId = 2; // hard-coded for testing _repository.CreateComment(commentToCreate); return View(); } catch { return View(); } }

    Read the article

  • How to initiate JavaScript Callback with MVC2 using RenderAction

    - by Zacho
    I am building a dashboard where I am iterating through a list of controls to render, and I need to initiate a general callback both after each control and after they are all completed. I was curious what the best way to handle this is. I can get the control specific callback fired off by placing myUserControlCallback(); in the user control itself. I'm just not sure how to run something like allControlsRendered();. Any ideas?

    Read the article

  • Html.ActionLink in Partial View

    - by olst
    Hi. I am using the following code in my master page: <% Html.RenderAction("RecentArticles","Article"); %> where the RecentArticles Action (in ArticleController) is : [ChildActionOnly] public ActionResult RecentArticles() { var viewData = articleRepository.GetRecentArticles(3); return PartialView(viewData); } and the code in my RecentArticles.ascx partial view : <li class="title"><span><%= Html.ActionLink(article.Title, "ViewArticle", new { controller = "Article", id = article.ArticleID, path = article.Path })%></span></li> The problem is that all the links of the articles (which is built in the partial view) lead to the same url- "~/Article/ViewArticle" . I want each title link to lead to the specific article with the parameters like I'm setting in the partial view. Thanks.

    Read the article

  • How to add a weather info to be evalueated only once???

    - by Savvas Sopiadis
    Hi everybody! In a ASP.MVC (1.0) project i managed to get weather info from a RSS feed and to show it up. The problem i have is performance: i have put a RenderAction() Method in the Site.Master file (which works perfectly) but i 'm worried about how it will behave if a user clicks on menu point 1, after some seconds on menu point 2, after some seconds on menu point 3, .... thus making the RSS feed requesting new info again and again and again! Can this somehow be avoided? (to somehow load this info only once?) Thanks in advance!

    Read the article

  • SharpDX: best practice for multiple RenderForms?

    - by Rob Jellinghaus
    I have an XNA app, but I really need to add multiple render windows, which XNA doesn't do. I'm looking at SharpDX (both for multi-window support and for DX11 / Metro / many other reasons). I decided to hack up the SharpDX DX11 MultiCubeTexture sample to see if I could make it work. My changes are pretty trivial. The original sample had: [STAThread] private static void Main() { var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample"); ... I changed this to: struct RenderFormWithActions { internal readonly RenderForm Form; // should just be Action but it's not in System namespace?! internal readonly Action RenderAction; internal readonly Action DisposeAction; internal RenderFormWithActions(RenderForm form, Action renderAction, Action disposeAction) { Form = form; RenderAction = renderAction; DisposeAction = disposeAction; } } [STAThread] private static void Main() { // hackity hack new Thread(new ThreadStart(() = { RenderFormWithActions form1 = CreateRenderForm(); RenderLoop.Run(form1.Form, () = form1.RenderAction(0)); form1.DisposeAction(0); })).Start(); new Thread(new ThreadStart(() = { RenderFormWithActions form2 = CreateRenderForm(); RenderLoop.Run(form2.Form, () = form2.RenderAction(0)); form2.DisposeAction(0); })).Start(); } private static RenderFormWithActions CreateRenderForm() { var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample"); ... Basically, I split out all the Main() code into a separate method which creates a RenderForm and two delegates (a render delegate, and a dispose delegate), and bundles them all together into a struct. I call this method twice, each time from a separate, new thread. Then I just have one RenderLoop on each new thread. I was thinking this wouldn't work because of the [STAThread] declaration -- I thought I would need to create the RenderForm on the main (STA) thread, and run only a single RenderLoop on that thread. Fortunately, it seems I was wrong. This works quite well -- if you drag one of the forms around, it stops rendering while being dragged, but starts again when you drop it; and the other form keeps chugging away. My questions are pretty basic: Is this a reasonable approach, or is there some lurking threading issue that might make trouble? My code simply duplicates all the setup code -- it makes a duplicate SwapChain, Device, Texture2D, vertex buffer, everything. I don't have a problem with this level of duplication -- my app is not intensive enough to suffer resource issues -- but nonetheless, is there a better practice? Is there any good reference for which DirectX structures can safely be shared, and which can't? It appears that RenderLoop.Run calls the render delegate in a tight loop. Is there any standard way to limit the frame rate of RenderLoop.Run, if you don't want a 400FPS app eating 100% of your CPU? Should I just Thread.Sleep(30) in the render delegate? (I asked on the sharpdx.org forums as well, but Alexandre is on vacation for two weeks, and my sister wants me to do a performance with my app at her wedding in three and a half weeks, so I'm mighty incented here! http://robjsoftware.org for details of what I'm building....)

    Read the article

  • Custom ViewEngine problem with ASP.NET MVC

    - by mare
    In this question jfar answered with his solution the problem is it does not work for me. In the method FindView() I have to somehow check if the View we are requesting is a ViewUserControl. Because otherwise I get an error saying: "A master name cannot be specified when the view is a ViewUserControl." This is my custom view engine code right now: public class PendingViewEngine : VirtualPathProviderViewEngine { public PendingViewEngine() { // This is where we tell MVC where to look for our files. /* {0} = view name or master page name * {1} = controller name */ MasterLocationFormats = new[] {"~/Views/Shared/{0}.master", "~/Views/{0}.master"}; ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx", "~/Views/{1}/{0}.ascx" }; PartialViewLocationFormats = new[] {"~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.ascx"}; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new WebFormView(partialPath, ""); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new WebFormView(viewPath, masterPath); } public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { if (controllerContext.HttpContext.Request.IsAjaxRequest()) return base.FindView(controllerContext, viewName, "Modal", useCache); return base.FindView(controllerContext, viewName, "Site", useCache); } } The above ViewEngine fails on calls like this: <% Html.RenderAction("Display", "WidgetZoneV2", new { zoneslug = "left-default-zone" }); %> As you can see, I am providing Route values to my RenderAction call. The action I am rendering here is this: // Widget zone name is unique // GET: /WidgetZoneV2/{zoneslug} public ActionResult Display(string zoneslug) { zoneslug = Utility.RemoveIllegalCharacters(zoneslug); // Displaying widget zone creates new widget zone if it does not exist yet; so it prepares our page for // dropping of content widgets WidgetZone zone; if (!_repository.IsUniqueSlug(zoneslug)) zone = (WidgetZone) _repository.GetInstance(zoneslug); else { // replace slug with spaces to convert it into Title zone = new WidgetZone {Slug = zoneslug, Title = zoneslug.Replace('-', ' '), WidgetsList = new ContentList()}; _repository.Insert(zone); } ViewData["ContentItemsList"] = _repository.GetContentItems(); return View("WidgetZoneV2", zone); } I cannot use RenderPartial (at least I don't know how) the way I can RenderAction. To my knowledge there is no way to provide RouteValueDictionary to RenderPartial() like the way you can to RenderAction().

    Read the article

  • How to check if returning View is of type PartialViewResult or a ViewUserControl

    - by mare
    In the method FindView() I have to somehow check if the View we are requesting is a ViewUserControl. Because otherwise I get an error saying: "A master name cannot be specified when the view is a ViewUserControl." This is my custom view engine code right now: public class PendingViewEngine : VirtualPathProviderViewEngine { public PendingViewEngine() { // This is where we tell MVC where to look for our files. /* {0} = view name or master page name * {1} = controller name */ MasterLocationFormats = new[] {"~/Views/Shared/{0}.master", "~/Views/{0}.master"}; ViewLocationFormats = new[] { "~/Views/{1}/{0}.aspx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx", "~/Views/{1}/{0}.ascx" }; PartialViewLocationFormats = new[] {"~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.ascx"}; } protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new WebFormView(partialPath, ""); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new WebFormView(viewPath, masterPath); // this line produces the error because we cannot set master page on ASCXs, so I need an "if" here } public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { if (controllerContext.HttpContext.Request.IsAjaxRequest()) return base.FindView(controllerContext, viewName, "Modal", useCache); return base.FindView(controllerContext, viewName, "Site", useCache); } } The above ViewEngine fails on calls like this: <% Html.RenderAction("Display", "MyController", new { zoneslug = "some-zone-slug" });%> The action I am rendering here is this: public ActionResult Display(string zoneslug) { WidgetZone zone; if (!_repository.IsUniqueSlug(zoneslug)) zone = (WidgetZone) _repository.GetInstance(zoneslug); else { // do something here } // WidgetZone used here is WidgetZone.ascx, so a partial return View("WidgetZone", zone); } I cannot use RenderPartial because you cannot send route values to RenderPartial the way you can to RenderAction. To my knowledge there is no way to provide RouteValueDictionary to RenderPartial() like the way you can to RenderAction().

    Read the article

  • Advice on displaying and allowing editing of data using ASP.NET MVC?

    - by Remnant
    I am embarking upon my first ASP.NET MVC project and I would like to get some input on possible ways to display database data and general best practice. In short, the body of my webpage will show data from my database in a table like format, with each table row showing similar data. For example: Name Age Position Date Joined Jon Smith 23 Striker 18th Mar 2005 John Doe 38 Defender 3rd Jan 1988 In terms of functionality, primarily I’d like to give the user the ability to edit the data and, after the edit, commit the edit to the database and refresh the view.The reason I want to refresh the view is because the data is date ordered and I will need to re-sort if the user edits a date field. My main question is what architecture / tools would be best suited to this fulfil my requirements at a high level? From the research I have done so far my initial conclusions were: ADO.NET for data retrieval. This is something I have used before and feel comfortable with. I like the look of LINQ to SQL but don’t want to make the learning curve any steeper for my first outing into MVC land just yet. Partial Views to create a template and then iterate through a datatable that I have pulled back from my database model. jQuery to allow the user to edit data in the table, error check edited data entries etc. Also, my intial view was that caching the data would not be a key requirement here. The only field a user will be able to update is the field and, if they do, I will need to commit that data to the database immediately and then refresh the view (as the data is date sorted). Any thoughts on this? Alternatively, I have seen some jQuery plug-ins that emulate a datagrid and provide associated functionality. My first thoughts are that I do not need all the functionality that comes with these plug-ins (e.g. zebra striping, ability to sort by column using sort glyph in column headers etc .) and I don’t really see any benefit to this over and above the solution I have outlined above. Again, is there reason to reconsider this view? Finally, when a user edits a date , I will need to refresh the view. In order to do this I had been reading about Html.RenderAction and this seemed like it may be a better option than using Partial Views as I can incorporate application logic into the action method. Am I right to consider Html.RenderAction or have I misunderstood its usage? Hope this post is clear and not too long. I did consider separate posts for each topic (e.g. Partial View vs. Html.RenderAction, when to use jQury datagrid plug-in) but it feels like these issues are so intertwined that they need to be dealt with in contect of each other. Thanks

    Read the article

  • how do i call an overloaded action in .net mvc?

    - by Jeff Martin
    I have an overloaded action in my Controller: public ActionResult AssignList(int id) { ... } [AcceptVerbs((HttpVerbs.Get))] public ActionResult AssignList(int id, bool altList) { ... } I'd like to use the same partial view for both lists but it will potentially have a differently filtered list of Images. I am trying to call it from another view using RenderAction: <% Html.RenderAction("AssignList", "Image", new { id = Model.PotholeId, altList = true }); %> However I am getting the following error: The current request for action 'AssignList' on controller type 'ImageController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult AssignList(Int32) on type UsiWeb.Controllers.ImageController System.Web.Mvc.ActionResult AssignList(Int32, Boolean) on type UsiWeb.Controllers.ImageController How can I call the specific overload?

    Read the article

  • MVC Serve audio files while preventing direct linking using HttpResponseBase

    - by VinceGeek
    I need to be able to serve audio files to an mvc app while preventing direct access. Ideally the page would render with a player control so the user can start/stop the audio linked to the database record (audio files are in a folder not the db). I have a controller action like this: Response.Clear(); Response.ContentType = "audio/wav"; Response.TransmitFile(audioFilename); Response.End(); return Response; and the view uses the RenderAction method <% Html.RenderAction("ServeAudioFile"); %> this works but it won't display inline on the existing view, it opens a new page with just the media control. Am I totally barking up the wrong tree or is there a way to embed the response in the existing view? works exactly as I would like but I can't control access to the file.

    Read the article

1 2 3  | Next Page >