How can I use Html.RenderPartial to get value - asp.net-mvc

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);

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.

RenderAction ViewBag Empty on the View

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?

from data to controller and passing it to form

I'm doing my first steps in mvc and I need help.
I'm passing data from view to this controller and I need to pass the selected items with there details to a different view (that is a form that the user add his email details) and I cant figure out how to .
This is how I'm getting the details to the controller from the submitted form
public ActionResult list()
{
var AllItems = db.menu.ToList();
Mapper.CreateMap<Menu, SelectableMenu>();
return View(AllItems.Select(m => new SelectableMenu { price = m.price, MenuId = m.MenuId, Name = m.Name })
.ToList());
}
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("bla");
}
return View();
}
Use method ReditectToActionstring actionName, string controllerName, Object routeValues)
for details go to: http://msdn.microsoft.com/en-us/library/dd460311(v=vs.108).aspx
You can return different view using return View("ViewName",model)
For eg:
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("YourDiffrentViewName",userSelectedMenu); // This will pass your model to your Different view
}
return View();
}
Then in your new view you will have to strongly typed it with your model.
For eg :
Your view will be as follows:
#model ProjectName.models.YourClassName //Your class/model namespace
#using(Html.BeginForm())
{
#Html.TextBoxFor(m => Model.Property) //This will create textbox for your property
<input type="submit" value="Submit" />
}
For more on stronly typed views visit:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/
http://www.howmvcworks.net/OnViews/BuildingAStronglyTypedView
You will need twosteps for this
Step 1
Make a model(it is more effective) use it in a view to pass your data to controller through post in submission of form.
Step 2
Receive the data into the controller method then use
return View("yourNewpage","yourdatamodelobject"); in the controller action to pass the data in the action result view of another page.
Alternatively, if the view is in another controller
then you can receive data here in the post action method and use Return RedirectToAction("ActionName", "ControllerName", "DataModelObject") to pass to a diffrent controller

How do you get route values in the view

Is there an alternative to get the route value in the view page instead of read it like querystring?
#Html.ActionLink("Language Resources", "Index", "LanguageResource",
new { languageCode = Request.QueryString["languageCode"] , "")
try to find from below code
In Razor
#{
var id = ViewContext.RouteData.Values["id"];
}
In WebForms:
<%
var id = ViewContext.RouteData.Values["id"];
%>
You can use RequestContext
#{
var id = HttpContext.Current.Request.RequestContext.RouteData.Values["id"];
}
Don't rule out keeping it simple:
public ActionResult Action(int id)
{
return View( id);
}
Indicate the type of the Model we're dealing with
#model int
And refer to the value in a strongly typed way via:
#Model
And for the less experienced out there, you can access the controller and the action parts of the URL too.
(Razor Example)
if(ViewContext.RouteData.Values["action"].ToString() == "Account")
{
#Html.Raw("Hi ") #Session["UserName"]
}
Where,
context.MapRoute(
name: "MyRoute",
url: "{controller}/{action}/{id}"
}

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.

Resources