I have a PartialView (_Letra) that receives information from a Controller named Music ... this way
public ActionResult CarregarLetra(string id, string artista, string musica)
{
return PartialView("_Letra", ArtMus(artista, musica));
}
public ResultLetra ArtMus(string artista, string musica)
{
//Conteúdo do metodo[..]
var queryResult = client.Execute<ResultLetra>(request).Data;
return queryResult;
}
Until then, no problem. What happens is that now I need to pass other information to this same PartialView (_Letra). This information is in PartialView (_Cifra).
So I added the following lines in my Music controller
public ActionResult CarregarCifra(string id, string artista, string musica)
{
return PartialView("_Cifra", GetCifra(artista, musica));
}
public ResultChords GetCifra(string artista, string musica)
{
var cfrTest= new Cifra();
var cifra = new ResultChords();
cifra.chords = cfrTest.GetInfs(artista, musica);
return cifra;
}
Everything working so far, PartialView _Cifra receives the information
I searched and found that I could use in PartialView _Letra the Html.Partial to load my PartialView _Cifra, I did this way then
I added
<div class="item">
<div class="text-carousel carousel-content">
<div>
#Html.Partial("_Cifra", new letero.mus.Infra.Models.ResultChords());
</div>
</div>
</div>
Now it starts to complicate why, the return of this is null, I believe it is due to a new instance of ResultChords that I make in Html.Partial
I have already tried using a ViewBag also to transpose the information between Partials, but probably not correctly, due to the return being null as well.
I've already done a lot of research and I'm not getting the information I need for PartialView _Letra.
There is a better way not to use Html.Partial, or to use it properly, as I am not aware.
In _Letra use
#Html.Action("CarregarCifra", "Music", new { id=Model.Id, artista=Model.Artista, musica=Model.Musica });
if the variables are available on the model then you can pass them in; otherwise, make use of the Viewbag and set them in CarregarLetra
Are you always passing a new object to the second partial? You could just create it at the top of the new _Cifra partial.
_Cifra.cshtml
#{
var resultChords = new letero.mus.Infra.Models.ResultChords();
}
Related
This is probably a very simple problem, but I am extremely new to C# / MVC and I have been handed a broken project to fix. So it's time to sink or swim!
I have an array of strings that is being passed from a function to the front end.
The array looks something like
reports = Directory.GetFiles(#"~\Reports\");
On the front end, I would like it to display each report, but I am not sure how to do that.
This project is using a MVC, and I believe the view is called "Razor View"? I know that it's using an HTML helper.
In essence, I need something like
#HTML.DisplayTextFor(Model.report [And then print every report in the array]);
I hope that makes sense.
If you want to display the file name array you can simply use a foreach:
#foreach(var report in Model.Reports){ #report }
Note that you should add the Reports property to your view model:
public class SampleViewModel
{
public string [] Reports { get; set; }
}
You could use ViewData or TempData but I find that using the view model is the better way.
You can then populate it:
[HttpGet]
public ActionResult Index()
{
var model = new SampleViewModel(){ Reports = Directory.GetFiles(#"~\Reports\")};
return View(model);
}
And use it in the view as you see fit.
Here is a simple online example: https://dotnetfiddle.net/5WmX5M
If you'd like to add a null check at the view level you can:
#if(Model.Reports != null)
{
foreach(var report in Model.Reports){ #report <br> }
}
else
{
<span> No files found </span>
}
https://dotnetfiddle.net/melMLW
This is never a bad idea, although in this case GetFiles will return an empty list if no files can be found, and I assume a possible IOException is being handled.
this is probably a pretty basic thing for you guys, but I still can't figure it out.
Let's say I have a View:
myView.cshtml
<div>
<p>Some content here</p>
#MyHTMLVariable //Calls updateHTML -> MyHTMLVariable = s
<p>Some more content over here</p>
</div>
myController.cs
public string updateHTML()
{
s = "I'm a string"; //Changes dynamically, handled by different stuff outside
//Any string to html-conversion needen?
return s;
}
How can I "update" the variable in the view / how do I have to initialize it?
Cheers,
DDerTyp
Use Razor's #functions code block to declare your functions within your view this way...
#functions {
public string updateHtml()
{
string s = "I'm a string";/*or whatever dynamic stuff you wanna do*/
return s;
}
}
#{
string myHtmlVariable = updateHtml();
}
Then use #myHtmlVariable within your code.
You can use the ViewBag for this. In your template use #ViewBag["MyHTMLVaribale"] and in your controller method use ViewBag["MyHTMLVariable"] = "I'm a string";
I'm working on a piece of code that shows a random sponsor image on each webpage. I figured that the best place to call my function is in the Views/Shared/_Layout.cshtml page, because that's the one that loads at every page.
I wrote the function in a service class in my domain model, and wrote a ChildActionOnly function in my homecontroller, returns the value in a simple view in Views/Home/Randomsponsor.cshtml and called the function in the shared layout with a Html.action.
Everything builds fine, but while running i get the next error:
{"The controller for path '/' was not found or does not implement IController."}
Does anyone know how to fix this one?
Method in the domain project:
public String advertsForCountry()
{
String studentSchool = finder.getLoggedStudent().SchoolId;
int studentCountry = db.Schools.Find(studentSchool).CountryId;
List<Sponsor> sponsorsForStudent = new List<Sponsor>();
List<Advert> adverts = db.Adverts.ToList();
foreach(Advert adv in adverts)
{
foreach(Country cntry in adv.Countries)
{
if(cntry.CountryId == studentCountry)
{
sponsorsForStudent.Add(adv.Sponsor);
}
}
}
Random random = new Random();
int randomSP = random.Next(0, sponsorsForStudent.Count()-1);
string sponsorAdvert = sponsorsForStudent.ElementAt(randomSP).SponsorCompany;
return sponsorAdvert;
}
In HomeController:
[HttpGet]
[ChildActionOnly]
public ActionResult RandomSponsor()
{
var model = service.advertsForCountry();
return PartialView("RandomSponsor", model);
}
Simple view in Views/Home/ :
#{
ViewBag.Title = "RandomSponsor";
}
#Html.Action("RandomSponsor")
And my function call in the View/Shared/_Layout.cshtml whitch contains the navigation bar, etc:
#Html.Action("RandomSponsor", "HomeController")
Regards.
(Converted from comment)
You don't need to specify the full class name of the Controller in Html.Action. Try using #Html.Action("RandomSponsor", "Home") instead of #Html.Action("RandomSponsor", "HomeController").
You are missing the name of the controller. Please note, when you create a controller and called it Alexie, by default MVC will name it AlexieController. Therefore, when you are calling a function within a controller, it should be like this:
#Html.Action("Function Name", "Alexie").
And not like this:
#Html.Action("Function Name", "AlexieController").
So, I agreed with wgraham's answer.
I have two different pages, from which a user can click on a 'details' link and go to the details page.
On the details page, I have a 'back' button, which leads the user to the originating page, being one of the two original pages of course.
There is also one extra issue: in one of the return links, I must specify an extra anonymous object.
my view code right now is:
#{
MvcHtmlString backLink = null;
if (Model.ReturnPage == MatchResultReturnPage.Search)
{
backLink = Html.ActionLink("GoBack", "Search", new {search = true});
}
else
{
backLink = Html.ActionLink("GoBack", "Dashboard");
}
}
In the controller I now look in the url.referrer if it contains 'dashboard', then I set the Model.ReturnPage to 'Dashboard'.
Is there a cleaner way of doing this?
Put the ReturnLink as a property on your model and set it inside the controller, which will alleviate the need for you to put that logic in the view.
There are certainly cleaner ways, but as your code is currently, it is very easy to understand what you are trying to do.
I would say keep it as is and simply put a #region wrapper around it and hide it when you don't need to work with it:
#region get referrer page
MvcHtmlString backLink = null;
if (Model.ReturnPage == MatchResultReturnPage.Search)
{
backLink = Html.ActionLink("GoBack", "Search", new {search = true});
}
else
{
backLink = Html.ActionLink("GoBack", "Dashboard");
}
#region
The only thing I would suggest is to have this check in the Controller, rather than the view and simply putting the result of your check either in model property, or in the ViewBag.
To gain access to Helpers in your controller, do the following:
var URL = new UrlHelper(this.Request.RequestContext).Action("MyAction", "MyController", new { id = 123 });
you should probably implement the Back button entirely in JavaScript.
using the history object
<a href=”javascript:history.back()”> [Back]</a>
I have a strongly-typed Partial View that takes a ProductImage and when it is rendered I would also like to provide it with some additional ViewData which I create dynamically in the containing page. How can I pass both my strongly typed object and my custom ViewData to the partial view with the RenderPartial call?
var index = 0;
foreach (var image in Model.Images.OrderBy(p => p.Order))
{
Html.RenderPartial("ProductImageForm", image); // < Pass 'index' to partial
index++;
}
RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:
Html.RenderPartial(
"ProductImageForm",
image,
new ViewDataDictionary { { "index", index } }
);
Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.
To extend on what womp posted, you can pass new View Data while retaining the existing View Data if you use the constructor overload of the ViewDataDictionary like so:
Html.RenderPartial(
"ProductImageForm",
image,
new ViewDataDictionary(this.ViewData) { { "index", index } }
);
#Html.Partial("_Header", new ViewDataDictionary { { "HeaderName", "User Management" }, { "TitleName", "List Of Users" } })
or
#{Html.RenderPartial("_Header", new ViewDataDictionary { { "HeaderName", "User Management" }, { "TitleName", "List Of Users" } });}
Partial Page(_Header):
<div class="row titleBlock">
<h1>#ViewData["HeaderName"].ToString()</h1>
<h5>#ViewData["TitleName"].ToString()</h5>
</div>
I think this should work no?
ViewData["currentIndex"] = index;
Create another class which contains your strongly typed class.
Add your new stuff to the class and return it in the view.
Then in the view, ensure you inherit your new class and change the bits of code that will now be in error. namely the references to your fields.
Hope this helps. If not then let me know and I'll post specific code.
I know this is an old post but I came across it when faced with a similar issue using core 3.0, hope it helps someone.
#{
Layout = null;
ViewData["SampleString"] = "some string need in the partial";
}
<partial name="_Partial" for="PartialViewModel" view-data="ViewData" />
The easiest way to pass additional data is to add the data to the existing ViewData for the view as #Joel Martinez notes. However, if you don't want to pollute your ViewData, RenderPartial has a method that takes three arguments as well as the two-argument version you show. The third argument is a ViewDataDictionary. You can construct a separate ViewDataDictionary just for your partial containing just the extra data that you want to pass in.
This should also work.
this.ViewData.Add("index", index);
Html.RenderPartial(
"ProductImageForm",
image,
this.ViewData
);
You can use the dynamic variable ViewBag
ViewBag.AnotherValue = valueToView;