Adding await to RenderPartialView produces an error - c#

This is an ASP.net core web application view. This works:
#if (r.Identifier.HasAcronym)
{
#Html.RenderPartialAsync("Resources", new Tuple<IEnumerable<FileSystemObject>, string>(r.ResourcesByAcronym, r.Identifier.Acronym));
}
this produces the error: Cannot implicitly convert type 'void' to 'object'
#if (r.Identifier.HasAcronym)
{
#await Html.RenderPartialAsync("Resources", new Tuple<IEnumerable<FileSystemObject>, string>(r.ResourcesByAcronym, r.Identifier.Acronym));
}

You can write like this:
<td>
#{
await Html.RenderPartialAsync("Resources", new Tuple......);
}
</td>
Html.RenderPartialAsync returns a Task, so the result type is void. The # without braces asks Razor to render the result, which is not possible: There is no way to convert void to anything renderable. This would only be the right way to go if Html.RenderPartialAsync returned a string, which needed to be rendered manually. The braces introduce a new code block, which allows standard C# syntax.

Related

is there a way to get a global variable to a view in asp.net/razor to use it to test in and if statement?

right now I am trying to only show a view in my project if my global var privacy is set to true. I am not sure how to call my global variable the same way I do in my controllers but is there a way that I am not thinking of? right now I am trying to call a function that tests this variable and outputs true or false so I can use it in an if statement this feels like a lot more work and I am having problems trying it this way so if there is any way else please let me know.
#if (Elearn.Controllers.AccountController.CheckGdpr())
{
<div class="popup">
<div id="consent-popup" class="hidden">
<p>
we advise our users to accept cookies for the best experience
<input class="btn-glow primary login" value="#_stringLocalizer["Accept Cookies"]" id="accept" />
</p>
</div>
</div>
}
controller function
public bool CheckGdpr()
{
string str = _configuration["privacy:GDPR"];
string checkbol = "True";
if (checkbol == str)
{
return true;
}
else
{
return false;
}
}
If someone knows how to correctly call a controller function too that would help a lot. I am getting an error
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'AccountController.CheckGdpr()' Elearn C:\Users\Isaac\source\repos\elearn2-final_sapce_fixes\Elearn\Elearn\Views\Account\LogOn.cshtml 74 Active
#if (Configuration.GetSection("privacy")["GDPR"] == "True")
this works

ASP.NET MVC RenderPartial Error Code CS0029

Not sure what went wrong, but the error is "CS0029: Cannot implicitly convert type 'void' to 'object'" at the Html.Partial.The other post said it should be enclosed with curved brackets, but its still not working (with and without). I have tried with Html.RenderPartial and Html.Partial, both don't work.
<div class="row" id="dtRecipe" style="margin-top:15px">
#*#{
Html.RenderPartial("_ListRecipe", new List<Eatery.Model.Models.Recipe>(), ViewData);
}*#
#Html.Partial("_ListRecipe", new List<Eatery.Model.Models.Recipe>(), ViewData);
</div>
The code for _ListRecipe is
public async Task<ActionResult> _ListRecipe()
{
int DishID = Convert.ToInt32(ViewData["DishID"]);
List<Recipe> recipes = (await recipeService.Get(DishID)).ToList();
return PartialView(recipes);
}
The recipeService is okay as it is used in another file.
Remove the ; at the end, it should be (without razor code block syntax):
#Html.Partial("_ListRecipe", new List<Eatery.Model.Models.Recipe>(), ViewData)
If you want to properly use Html.RenderPartial, this is the right type of syntax (See code below), which means you need to create a razor syntax code block and there is a ; at the end:
#{
Html.RenderPartial("_ListRecipe", new List<Eatery.Model.Models.Recipe>(), ViewData);
}

System.Web.HttpParseException: 'Unexpected "{" after "#" character

I'm getting this exception while trying to render PartialView. When I change #{Html.RenderPartial("_ChildReplies", parRep.ChildReplies);}
to
#Html.Partial("_ChildReplies", parRep.ChildReplies) still getting same exception.
#model List<Reply>
#using YourPlace.Models
<ul>
#foreach (var parRep in Model)
{
<li>
Author: #parRep.AuthorName
Comment: #parRep.AuthorName
<div>
#{Html.RenderPartial("_ChildReplies", parRep.ChildReplies);}
</div>
</li>
}
</ul>
The code above looks correct... if you are getting this error, it is probably because something is going wrong inside _ChildReplies partial view which you have not shown in your question...
Good explanation here:
RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by
{ }.
Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a
# prefix to distinguish it from plain HTML you have on the page.
So you need to either use this:
#{ Html.RenderPartial("_ChildReplies", parRep.ChildReplies); }
Or this:
#Html.Partial("_ChildReplies", parRep.ChildReplies);

MVC Html.Hidden - # does make a difference

I have the following piece of code :
#if (Model.A == Model.B)
{
Html.Hidden("a1", Model.A1);
}
else
{
Html.Hidden("a2", Model.A2);
}
With the above piece of code the hidden fields are not created and I don't get any errors.
After 30 minutes I realized that if I put the # behind Html.Hidden it works :
#if (Model.A == Model.B)
{
#Html.Hidden("a1", Model.A1);
}
else
{
#Html.Hidden("a2", Model.A2);
}
Any ideas ?
Thanks
Html is a form property that maps to an instance of HtmlHelper. HtmlHelper.Hidden returns a MvcHtmlString
Html.Hidden("a1", Model.A1);
does nothing as the returned value is not captured. You don't get any errors because it's perfectly valid C# code (capturing the return is optional). Most static analysis tools, however, will warn you about this since it's most likely a bug (as you have discovered).
On the other hand,
#Html.Hidden("a1", Model.A1);
is analagous to
Response.Write(Html.Hidden("a1", Model.A1));
which writes the return value to the HTML response.

Using a C# list in a javascript snippet

I want to use two arrays from C# in the JS snippet in a view. In order to do so I've tried to use the JavaScriptSerializer() but the data array isn't getting any values (the view's source shows it as follows):
var mydata =
Every example I've come across injects the C# code in JS by using <%=%> tags. This doesn't yield any results for me since I'm using ASP.NET MVC 4. Therefore I tried it with the following:
<script type="text/javascript">
var mydata = #{ new JavaScriptSerializer().Serialize(Model.GetData());}
$(function () {
// Generates a chart using the mydata array
}
</script>
What's wrong about this syntax? When I try to add an array for the headers underneath it, I receive a compilation error. There are warnings that the lines aren't terminated, but when I add ; at the end of each line it gives a syntax error as well (no specific error, just 'syntax error').
The data in GetData() and GetHeaders() are defined as such:
public List<int> GetData() {
return new List<int>(new[] { 4, 5, 6});
}
I've tried returning it as a int[] but this made no difference.
How can I use a C# list/array in a JavaScript snippet?
Edit: image of the unknown compilation error.
When I don't place the semicolons I get a syntax error on the second var. I get a suggestion to terminate the line endings, which adds the semicolons to the end. Then I have the issue as shown below. Curious detail: there are no red bars to the side of the file that usually indicate where the error is located.
That being said: when executing the script, the arrays have their expected values and everything works as it should.
The problem is that #{ } creates a block of code, it doesn't print the result to the rendered page. You can do this:
#{
var serializer = new JavaScriptSerializer();
#serializer.Serialize(Model.GetData())
}
Or even better, use the Json helper:
#Json.Encode(Model.GetData())
When you enclose operations within code blocks the output won't be rendered unless you explicitly tells it to render.
Try this one:
#Html.Raw(Json.Encode(Model.GetData()))
Try to put the result of the serializer in single quotes, like:
<script type="text/javascript">
var data = '#{ new JavaScriptSerializer().Serialize(Model.GetData());}';
</script>
You can create a HTML helper to call this, example:
<script type="text/javascript">
var data = '#Html.JSSerializerHelper(Model.GetData())';
</script>
Only one way that I think most elegant.
You could convert your List into JavaScript array to use within js.
Try this:
<script type="text/javascript">
var mydata = [];
#foreach(int i in Model.GetData()) {
<text>mydata.push(#i);</text>
}
$(function () {
// Generates a chart using the mydata array
}
</script>

Categories

Resources