#RenderPage - Render a edit page - asp.net-mvc

I want to render a page but that page be a "edit" page. Something like this
#RenderPage("~/Views/Edit/25.cshtml")
But this doesn't work and probably i should pass the parameter "25" as a parameter, but so far without success. In my program I've got two tabs and both call(render) pages throw Ajax (Jqueryui - http://jqueryui.com/tabs/) and i would like to when i click in a tab he call the edit view with a specific id.
It's possible? How i should do that?

To render tabs via ajax in asp.net mvc you can do it this way.
CSHTML:
Create tab control, each anchor in tab header uses different routevalues. Ofcourse you can link them to different actions of controller:
<div id=tabs>
<ul>
<li>#Html.ActionLink("Tab1", "Edit", new { id = 25 })</li>
<li>#Html.ActionLink("Tab2", "Edit", new { id = 26 })</li>
</ul>
</div>
Controller, note that you are returning a partial view here which gets rendered into the tabcontrol:
public ActionResult Edit(int id)
{
// You probably want to load the Model from the db with id param. I just write a message
ViewBag.Message = id;
return PartialView("Edit");
}
My partialview Edit.cshtml:
<span>Edit me #ViewBag.Message</span>
Javascript, just create your tab control normally:
$("#tabs").tabs();
Generally if you want to render some partial view with parameters I'd personally go for
#Html.Action("Edit", "Controller", new {id=25})

If you want some actions to be performed on click for the specific tab then i would suggest you should go with Ajax.
Have a look to jQuery.Ajax.
Or else you want it a pure http web request, then you can have certain query string to be passed on the same page when user clicks on the tab and load the content accordingly by identified the passed value.

Related

Partial Views on mvc create view that use a dropdown list to populate the partial view's view bag is this possible in mvc?

can a Partial Views on mvc create view that is using a dropdown list that sends value from the dropdown list to a function that creates a list based on the dropdown list value selection, That is then stored in a view bag for the partial view.. Can this be done in mvc and can it be done on create view of a mvc form?
I can see how something this would work in the edit view because the dropdown list value has already been selected when the page loads.
But on a new Create view record nothing is selected so the list function has a null value
Are partial views only for forms that have data pre-populated in them?
Update:
I have a create view that was created by the visual studio wizard. It has both a post and get under the create. When the user in the create view. I have a dropdown list on the page form with other fields but on load of that new create page it is empty. Unfortunately for me I wanted my partial view to to get populated with a list of data that gets sent to a view bag after the user make a selection from the drop down list.
I think what I am asking to do can only be done with webforms as mvc can handle dynamic data all that well it seems. And since when the page loads the dropdown has no value.. the list can't built so there is a null value error as well as and empty list if I hard code a value in the drop down list.
Here is my Code in these different attempt threads with different veration of my code documenting my many attempts. As I have comcluded it is not possible sadly.
Can a Drop Down List Trigger A Partial View To Update on A Create View Form In mvc?
Null view bag and partial view
Populating Partial Views using mvc
Updating a Partial View in MVC 5
So with help from Matt Bodily You can Populate a Partial View in the create view triggered by a changed value in a drop down list using a view bag and something called Ajax. Here is how I made my code work.
First the partial view code sample you need to check for null data
_WidgetListPartial
#if (#ViewBag.AList != null)
{
<table cellpadding="1" border="1">
<tr>
<th>
Widget Name
</th>
</tr>
#foreach (MvcProgramX.Models.LIST_FULL item in #ViewBag.AList)
{
<tr>
<td>
#item.WidgetName
</td>
</tr>
}
</table>
}
Populating your View Bag in your controller with a function
private List<DB_LIST_FULL> Get_List(int? VID)
{
return db.DB_LIST_FULL.Where(i => i.A_ID == VID).ToList();
}
In your Create controller add a structure like this using the [HttpGet] element
this will send you data and your partial view to the screen placeholder you have on your create screen The VID will be the ID from your Drop down list this function also sends back the Partial View back to the create form screen
[HttpGet]
public ActionResult UpdatePartialViewList(int? VID)
{
ViewBag.AList = Get_List(VID);
return PartialView("_WidgetListPartial",ViewBag.AList);
}
I am not 100% if this is needed but I added to the the following to the ActionResult Create the form Id and the FormCollection so that I could read the value from the drop down. Again the Ajax stuff may be taking care if it but just in case and the application seems to be working with it.
This is in the [HttpPost]
public ActionResult Create(int RES_VID, FormCollection Collection, [Bind(Include = "... other form fields
This is in the [HttpGet] again this too may not be needed. This is reading a value from the form
UpdatePartialViewList(int.Parse(Collection["RES_VID"]));
On Your Create View Screen where you want your partial view to display
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PV_WidgetList">
#{ Html.RenderAction("UpdatePartialViewList");}
</div>
</div>
And finally the Ajax code behind that reads the click from the dropdown list. get the value of the selected item and passed the values back to all of the controller code behind to build the list and send it to update the partial view and if there is data there it pass the partial view with the update list to the create form.
$(document).ready(function () {
$('#RES_VID').change(function ()
{
debugger;
$.ajax(
{
url: '#Url.Action("UpdatePartialViewList")',
type: 'GET',
data: { VID: $('#RES_VID').val() },
success: function (partialView)
{
$('#PV_WidgetList').html(partialView);
$('#PV_WidgetList').show();
}
});
This many not be the best way to do it but this a a complete an tested answer as it work and it is every step of the process in hopes that no one else has to go through the multi-day horror show I had to go through to get something that worked as initially based on the errors I thought this could not be done in mvc and I would have to continue the app in webforms instead. Thanks again to everyone that helped me formulate this solution!
No, partial views do not necessarily have to be strongly typed, if that's your question. You can have a partial view with just html markup.

passing the original controller and action name - mvc

I have an ascx control for fruits that contains following code:
<div id = "fruits">
....
Ajax stuff1 UpdateTargetId = "fruits"
Ajax stuff2 UpdateTargetId = "fruits"
<%Html.RenderPartial("PagerAjax", (Pager)ViewData["pager"]); %>
</div>
now this fruit control can appear on a number of webpages and the pager would need to know what page the user is on so that it can pull next set of fruits accordingly. For example, if I am on red-fruit page, then PagerAjax should know I am only pulling out red fruits. So, basically I would need to know ControllerName (assume it's home) and actionName (assume it's redFruits()). (Example may seem inefficient but it makes sense for the real purpose.) Now, I could do something like this:
<%Html.RenderAction("PagerAjax", (Pager)ViewData["pager"], ViewContext.RouteData.Values["action"], controllerFilter = ViewContext.RouteData.Values["controller"] }); %>
However, as you noticed, the above RenderAction is inside the div that is being updated by Ajax callback, which means it will contain action and controller of the Ajax stuff rather than the original URL's.
What should be an efficient workaround?
You could pass the original ViewContext.RouteData.Values["action"] as parameter when calling your AJAX action. This way the action knows what was the original action and store it in the model (or ViewData as in your case I see that your views are not strongly typed). Now your markup could become:
<% Html.RenderPartial(
"PagerAjax",
(Pager)ViewData["pager"],
new ViewDataDictionary() { { "originalAction", ViewData["originalAction"] } }
); %>

Obtain View name in Controller, ASP.NET MVC

I am using asp.net mvc. I have 4 pages that show list of events(different type of events) and "Details" link on each page leads to "EventDescription.aspx" View.
The "EventDescription.aspx" has a link called "Back to Events" which has to take the user to the appropriate page.
Eg: if the "Details" request came from page1 the "Back to Events" link needs to point to page1.aspx. Same for page2.aspx,page3.aspx,page4.aspx.
My plan is to capture the view name (page1.aspx) in controller action "EventDescription" and store in ViewData before displaying the "EventDescription.aspx" and user the ViewData value for "Back to Events" link.
How to obtain the name of the View from where the request comes from inside a Action?
Thank in advance.
When you render the page, you also need to render a link that will point to the correct page when Back to Events is clicked. This is best set up in the controller method, where you readily have access to all of the necessary information.
An easy way to do this is to put the return link information in a ViewData variable (untested pseudocode follows). In your controller method:
ViewData["ReturnPath"] = "/Content/Page/1";
And then in your view:
<% =Html.ActionLink("Back To Events", ViewData["ReturnPath"]) %>
or something similar.
Alternatively, you could try something like
ViewContext.RouteData.Values["action"]
...if you don't mind the magic string there. This will give you the calling action.
if you just want to get the Url where you came from you can do this in your Action
ViewData["ReturnPath"] = this.Request.UrlReferrer.AbsolutePath;
This give you the Url of the page where you came from. If your from Page1 then you go to EventDescription. In your EventDescription Action, your ReturnPath ViewData has the Url of Page1. Or Vice Versa.
I suggest you use TempData instead of ViewData. For instance you could have a setting like this.
public ActionResult Details(int id)
{
var event = repository.GetByID(id);
if (event != null)
{
TempData["ReturnPath"] = Request.UrlReferrer.ToString();
return View(event);
}
else { //....... ; }
}
And in your View you could have a regular ActionLink like so
<% =Html.ActionLink("Back To Events", TempData["ReturnPath"]) %>
If you want to be DRY, you could also create an Action method in your controller just to handle the redirects like so.
public ActionResult GoBack()
{
return Redirect(TempData["ReturnPath"]);
}
And in your View a normal ActionLink like so
<% =Html.ActionLink("Back To Events", "GoBack") %>
Put the return path in TempData (not ViewData) and it can pass from the calling page to the Details page. See also http://jonkruger.com/blog/2009/04/06/aspnet-mvc-pass-parameters-when-redirecting-from-one-action-to-another/

asp.net mvc actionlink shows address in FF, cannot get button to function

I'm currently in the process of learning ASP MVC and am running into a few issues.
First, when I use
<%=Http.ActionLink("Add / Modify", "AddModify" %>
it will show as Add / Modify (/Home/AddModify) in Firefox and Add / Modify in IE. It is doing that to all links in FF and none in IE. Anyone know what reasoning is for that?
Edit: What is displayed in the browser (FF in this case) is "Add / Modify (/Home/AddModify)" while in IE shows just "Add / Modify".
Here is a screenshot of what I see on my site in FireFox: http://img6.imageshack.us/img6/1331/19748435.png
You can see how it shows the text and the appropriate link afterwards (only populated in Database with /).
Also, I am trying to have buttons (both standard and image) on my site which will link to new pages, while also performing hidden tasks (saving data, etc...). Anyways, When I do the following:
<form method="post" action="/Home">
<input type="submit" value="AddModify">
</form>
and the controller has a simple
[ActionVerbs(HttpVerbs.Post)]
public ActionResult AddModify()
{
return View();
}
And I still cannot get that function to call, yet when I do http://localhost:port/Home/AddModify, the function calls and I can get to that page. I am doing it this way because there may be code that has to execute before redirecting to that page, rather than just a direct link to that page. I have tried with and without the ActionVerbs line, I have tried this form of the Html Form:
<% using (Html.BeginForm()) { %> ... <%}%>
and still nothing. I have also tried no form and still nothing, but here's something that may affect this...I am using a master page with everything inside a content place holder inside a form that uses runat="server". Would that matter? So its Master Page -> form (masterform runat server) -> ContentPlaceHolder -> form (for postback and action) -> submit button. Any help would be greatly appreciated.
If I am thinking correctly, your form action should be calling the name of the action method:
<form method="post" action="/Home/AddModify">
<input type="submit" value="AddModify">
</form>
The ActionLink would be the same way.
Otherwise you will need to modify your routes to go to that action method by default.
Let's do this in two parts
1 I think your ActionLink should be:
<%=Http.ActionLink("Add / Modify", "AddModify", "Home")
...to force routes.
First parameter: text shown
Second parameter: action name
Third parameter: controller name
2 Change your submit button to: (I assume we're currently looking at your "index" action from your "Home" controller)
<form method="post" action="/Home">
<input type="submit" value="AddModify" name="ModifyBtn" >
</form>
Then in your Home controller:
edit:
//GET
public ActionResult Index()
{
return View();
}
/edit
[ActionVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form, string ModifyBtn, string OtherBtn)
{
if (ModifyBtn!=null)
{
//do stuff
return RedirectToAction("AddModify");
}
if (OtherBtn!=null)
{
//do stuff
return RedirectToAction("OtherAction");
}
return View();
}
edit:
I think you're trying to submit directly to another Action. The best way is to handle the POST method inside your code then redirect to another action. That way, you can use
<% using (Html.BeginForm()) { %>
without trouble.
<form method="post" action="/Home">
Will create a form with a href of /Home, this will only call the AddModify action if the AddModify action is default on that route.

Render action return View(); form problem

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();
}
}
The answer is to use return RedirectToAction(). Using this enforces the PRG pattern and achieves my goal.
My earlier comment to my original post did cause an error, that I guess I'm still confused about, but this works:
return RedirectToAction("Details", "Steps", new { id = "2" });
I, and this is a personal opinion, think you've tackled this the wrong way.
Personally I would;
Create a view called ListStories.
Create a partial view that lists the
stories.
Create a partial view to create a
story.
When you want to add a story, simply
show the add story html.
Then when the user presses a button
you do a jQuery postback, add the
new story and return a PartialView
of either the new story or all the
stories.
If you return a partial view of all
stories then replace the bounding
div that contains all the stories
with the new data.
If you return only a single story
then append it to the end of the div
containing the stories.
I know this means a lot of re-work and it sounds complex and like a lot of work but doing it like this means greater flexibility later on because you can re-use the partial views or you can make a change once and all views using that partial view are now updated.
also, using jQuery means that the adding of stories looks seemless w/out any obvious post back which is nice.
Since the problem seems to be caching, you can simply disable/limit caching.
Add the following attribute to your actions:
[OutputCache(Duration = 0, VaryByParam = "none")]
This will tell the browser to cache the page, but for 0 seconds. When the post reloads the page, you should see the desired results.
The answer is to make sure your form action is properly set. If you have used renderaction and not set the form controller and action manually then the action will be the current URL.
Try:
<% using (Html.BeginForm("ActionName", "ControllerName")) {%>
Instead of:
<% using (Html.BeginForm()) {%>

Resources