RenderAction ViewBag Empty on the View - asp.net-mvc

I am invoking a RenderAction from a View as shown below:
#{ Html.RenderAction("GetOptions", "Product", new {ProductId = Model.ProductId});
var options = ViewBag.Options;
}
Inside the GetOptions I populate the ViewBag as shown below:
public ActionResult GetOptions(..) {
// do some other stuff
ViewBag.Options = new JavaScriptSerializer().Serializer(options);
return Content(somelongstring);
}
But when I debug inside the var options is always null. What am I doing wrong?

Related

IEnumerable<Twitter Status> View Output MVC 5

I am trying to output a set of tweets with a certain hashtag.
I have the following code in the controller:
public ActionResult Test() {
var service = new TwitterService("xxx", "xxx");
service.AuthenticateWith("xxx", "xxx");
var options = new SearchOptions { Q = "#test" };
TwitterSearchResult tweets = service.Search(options);
IEnumerable<TwitterStatus> status = tweets.Statuses;
ViewBag.Tweets = status;
//var tweets = service.Search(options);
return View();
}
I want to output the results that are in the IEnumerable in a view.
But I am finding it difficult to output these results in a view. Can anyone help please?
Your question is a bit vague but I think I understand your problem.
You'll want to pass the data into your view from your action.
public ActionResult Test() {
var service = new TwitterService("xxx", "xxx");
service.AuthenticateWith("xxx", "xxx");
var options = new SearchOptions { Q = "#test" };
TwitterSearchResult tweets = service.Search(options);
IEnumerable<TwitterStatus> status = tweets.Statuses;
//var tweets = service.Search(options);
return View(status);
}
Notice I pass in the status object into the view.
Now in your view you can just bind that object.
#model IEnumerable<TwitterStatus>
#foreach(var status in Model){
<div>
#status.Id #*Id is an exmaple property. Use the actual properties inside "TwitterStatus"*#
</div>
}
Edit:
If you want to have multiple things inside your page you'll have to use Partial Views.
You'll need a view that will encompass all your other partial views. To do this, just define a action for your twitter info that will be your parent view.
public ActionResult AllInfo() {
return View();
}
Then your razor:
//AllInfo.cshtml
#Html.Action("Test", "YourController")
In AllInfo.cshtml we call the action "Test" inside "YourController". We'll change "Test" to return a PartialView instead of a View.
public ActionResult Test() {
var service = new TwitterService("xxx", "xxx");
service.AuthenticateWith("xxx", "xxx");
var options = new SearchOptions { Q = "#test" };
TwitterSearchResult tweets = service.Search(options);
IEnumerable<TwitterStatus> status = tweets.Statuses;
return PartialView(status);
}
The razor stays the same for your partial view:
//Test.cshtml
#model IEnumerable<TwitterStatus>
#foreach(var status in Model){
<div>
#Model.Id #*Id is an exmaple property. Use the actual properties inside "TwitterStatus"
</div>
}
You can call #Html.Action() as many times as you want in your AllInfo.cshtml page and add all the PartialViews you need.

Parameter passing in an MVC Controller

I have the following ActionResult in my controller
[HttpGetAttribute]
public ActionResult _UpdateAlertNote(int recordId)
{
DealActionUpdateAlertNoteViewModel vm = new DealActionUpdateAlertNoteViewModel();
dtDeal_v10_r1.Manager objMan = new dtDeal_v10_r1.Manager(ref mobjSecurity);
dtDeal_v10_r1.Deal objDeal = default(dtDeal_v10_r1.Deal);
objDeal = objMan.GetDealObject(recordId, true);
vm.Message = objDeal.AlertMessage;
vm.IsDefaultStyle = objDeal.Alert_UseDefaultStyle;
vm.BackgroundColor = objDeal.Alert_BackgroundColor;
vm.FontColor = objDeal.Alert_FontColor;
vm.DealId = recordId;
return PartialView(vm);
}
Also the following ActionResult
[HttpPost]
public ActionResult _UpdateAlertNote(DealActionUpdateAlertNoteViewModel vm)
{
dtDeal_v10_r1.Manager objMan = new dtDeal_v10_r1.Manager(ref mobjSecurity);
objMan.UpdateAlertMessage(vm.DealId, vm.Message, vm.IsDefaultStyle, vm.FontColor, vm.BackgroundColor);
return this.PartialView("_action", vm.DealId);
}
When I execute this code it the "DealId" comes up as 0 in the Post.
I checked the Get and the DealId is being stored in the vm.DealId but is not passed through to the Post method.
I am not sure why it isn't passing could someone help me out with this.
****EDIT json added***
DealerSocket.TakeAction.updateDealAlertNote = function () {
var controller = "/DealAction/_UpdateAlertNote?mDeal_ID=";
var formId = "_UpdateDealAlertNoteFormElement";
DealerSocket.TakeAction.PostActionAndRefresh(formId, controller);
};
When you are posting an HTML Form element to a POST action, you need to make sure the value you pass to the view is stored in a Form element.
In this case of yours you will need something like:
<input type="hidden" value="#vm.DealId" />
within the <form> tag that you are Posting to the action.
Only elements inside the <form> tag will be serialized and sent to the Action.

How can I use Html.RenderPartial to get value

I have this My view
#model WebSite.Models.mymodelModel
#{ ViewBag.Title = "AudioPlayer2"; }
<div>
#{Html.RenderAction("AudioPlayer", "mycontroller", new { storyId = 3027, className = "" });}
</div>
this is my complete view and
this method in my controller
public PartialViewResult Audioplayer2()
{
return PartialView();
}
after that it calls another method in controller which name is Audioplayer
but the probelm is I set StoryId static in
#{Html.RenderAction("AudioPlayer", "mycontroller", new { storyId = 3027, className = "" });}
but the correct way to get the storyId is from #model.str.StoryId but
The #model comes null all the time. So, how can I use Html.RenderPartial to get the #model.str.storyId which I can get from controller as
List<str> rtn = new List<str>();
rtn = GetLatestEpisodes(DateTime.Now.AddMonths(-3).ToString(), DateTime.Now.ToString(), 0, 1);
storyId is the rtn.stroryId
but until this moment I can't get it
You should access your model in the razor view with Model variable and not model (Note the capital M, it makes a difference) like so: Model.storyId
Also ensure in your controller you are passing the variable rtn to the view like so: return View(rtn);

Pro Asp.net mvc 2: Problem in example

I am trying to recreate an example from Chapter-5 of book Pro Asp.net MVC2. But as soon as I add Menu code server stops working. Any Problem with the code?
public class NavController : Controller
{
private IProductRepository productsRepository;
public NavController(IProductRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult Menu()
{
Func<string, NavLink> makeLink = categoryName => new NavLink
{
Text = categoryName ?? "Home",
RouteValues = new RouteValueDictionary( new {
controller = "Products", action = "List", category = categoryName, page = 1
})
};
List<NavLink> navLinks = new List<NavLink>();
navLinks.Add(makeLink(null));
var categories = productsRepository.Products.Select(x => x.Category);
foreach (string categoryName in categories.Distinct().OrderBy(x => x))
navLinks.Add(makeLink(categoryName));
return View(navLinks);
}
}
Menu.cshtml
#model IEnumerable<SStore.WebUI.Models.NavLink>
#foreach (var link in Model)
{
Html.RouteLink(link.Text, link.RouteValues);
}
If I remove this line from my master page then server works
#{
Html.RenderAction("Menu", "Nav");
}
otherwise getting this error
Html.RenderAction("Menu", "Nav");: That's horrible recursion: Nav/Menu which renders Nav/Menu which renders Nav/Menu, ..., until you run out of stack and your web server blows :-)
When you render a child action like this ensure it has no master or the master's gonna rerender it again and again and again, .... So modify this view (~/Views/Nav/Menu.cshtml) like this:
#model IEnumerable<SStore.WebUI.Models.NavLink>
#{
Layout = null;
}
#foreach (var link in Model)
{
Html.RouteLink(link.Text, link.RouteValues);
}
Let me explain:
The example you saw in the book was using the WebForms view engine. In this view engine you have .aspx (views) and .ascx (partials). I suppose that in the book they were using Menu.ascx which by default has no master because it is a partial.
In Razor there is no longer such distinction. You simply have views: .cshtml pages. It is up to you to control whether they have a master or not. There are different ways. One is what I showed previously, another is to return PartialView(navLinks) inside the child action.

How to get current controller and action from inside Child action?

I have a portion of my view that is rendered via RenderAction calling a child action. How can I get the Parent controller and Action from inside this Child Action.
When I use..
#ViewContext.RouteData.Values["action"]
I get back the name of the Child Action but what I need is the Parent/Calling action.
Thanks
BTW I am using MVC 3 with Razor.
And if you want to access this from within the child action itself (rather than the view) you can use
ControllerContext.ParentActionViewContext.RouteData.Values["action"]
Found it...
how-do-i-get-the-routedata-associated-with-the-parent-action-in-a-partial-view
ViewContext.ParentActionViewContext.RouteData.Values["action"]
If the partial is inside another partial, this won't work unless we find the top most parent view content. You can find it with this:
var parentActionViewContext = ViewContext.ParentActionViewContext;
while (parentActionViewContext.ParentActionViewContext != null)
{
parentActionViewContext = parentActionViewContext.ParentActionViewContext;
}
I had the same problem and came up with same solution as Carlos Martinez, except I turned it into an extension:
public static class ViewContextExtension
{
public static ViewContext TopmostParent(this ViewContext context)
{
ViewContext result = context;
while (result.ParentActionViewContext != null)
{
result = result.ParentActionViewContext;
}
return result;
}
}
I hope this will help others who have the same problem.
Use model binding to get the action name, controller name, or any other url values:
routes.MapRoute("City", "{citySlug}", new { controller = "home", action = "city" });
[ChildActionOnly]
public PartialViewResult Navigation(string citySlug)
{
var model = new NavigationModel()
{
IsAuthenticated = _userService.IsAuthenticated(),
Cities = _cityService.GetCities(),
GigsWeBrought = _gigService.GetGigsWeBrought(citySlug),
GigsWeWant = _gigService.GetGigsWeWant(citySlug)
};
return PartialView(model);
}

Resources