unexpected "{" after # in razor code in mvc4 - asp.net-mvc-4

I am getting below error in render partial in razor code, Unexpected "{" after "#" character. Once inside the body of a code block (#if {}, #{}, etc.) you do not need to use "#{" to switch to code.
#if (Model.Count() > 0)
{
<div id="mReserveForTodayPartial">
#{Html.Partial("UpdateReserveForToday.mobile");}
</div>
}
kindly help..!

Html.Partial() return MvcHtmlString so you have to do like this:
#Html.Partial("UpdateReserveForToday")
in Html.RenderPartial() case it writes to the output stream and that's why it's return type is void, so when using Html.RenderPartial() you have to do this:
#{
Html.RenderPartial("UpdateReserveForToday");
}

try this code:
#{ List<SelectListItem> listItems = new List<SelectListItem>();
foreach (var item in ViewData["Subcategory"] as IEnumerable<ApplicationOneStoreForEstore.Models.tblsubcategory>) {
listItems.Add(new SelectListItem {
Text = item.subcategory_name,
Value = Convert.ToString(item.subcategory_id)
});
}
}
If you have to bind DropDownList then You have to placed this code before Html.BeginForm(..)

Below code should resolve this issue.
#if (Model.Count() > 0)
{
<div id="mReserveForTodayPartial">
Html.Partial("UpdateReserveForToday.mobile");
</div>
}
As Razor view engine can parse the code if the statements are available with in "#{ }", So in your code "#{}" is present at "If" statement so its not required to specify again.

Related

What is causing __builder does not exist in current context error from compiler?

"Error CS0103 The name '__builder' does not exist in the current context"
Here is my code that causes the error:
#code {
public void Calc()
{
for (int i = 0; i < 55; )
{
<div class="alert-info">
<h3>This is the number" #i</h3>
</div>
}
}
}
You can't render HTML in #code or #functions block. You can do this in a #{ } code bock.
As per ltwlf's answer, HTML markup is not allowed within the #Code block. I received the same error, but I was positive that I had no HTML within my #code block. However, after careful review I noted that there were HTML comment tags <!-- ... --> inside my #code block. This displays correctly as green comments and is easily missed - Therefore carefully review your #code block for any HTML markup if you get this error.
The correct answer is at this SO link.
In short you cannot mix markup with C# code inside #code block.
Consider make a component for reusing the markup.
Members of the component class are defined in one or more #code blocks. In #code blocks.
Component members are used in rendering logic using C# expressions that start with the # symbol. For example, a C# field is rendered by prefixing # to the field name.(more info)
The RenderFragment delegate must accept a parameter called __builder of type RenderTreeBuilder so that the Razor compiler can produce rendering instructions for the fragment.
Sample1:
#using Microsoft.AspNetCore.Components.Rendering
#{ load1(__builder); }
#code {
void load1(RenderTreeBuilder __builder)
{
#for (int i = 0; i < 1; i++)
{
<div class="alert-info">
<h3>This is the number #i</h3>
</div>
}
}
}
Sample2:
<button class="btn btn-success" #onclick="()=>Calc()">Action</button>
#((MarkupString)myMarkup)
#code {
string myMarkup = "";
void Calc()
{
#for (int j = 0; j < 55; j++)
{
myMarkup += getMarkup(j);
}
}
string getMarkup(int j) {
var myMarkup = "<div class='alert-info'>";
myMarkup += $"<h3>This is the number {j}</h3>";
myMarkup += "</div>";
return myMarkup;
}
}
In order to use the "onclick" within a razor page you must prefix it with the # symbol.
Event Handling

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'BranchQuickChange'

I've been on this error for a while and the ienumerable object is blocking can someone pls help me the error is in the description.
HTML:
#model IEnumerable<DatabaseDAL.Models.WAGTripHdr>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$("select#BranchQuickChange").change(function () {
var branchName = $("select#BranchQuickChange option:selected").text();
alert(branchName);
window.location.href = '#Url.Action("QuickBranchChange", "TripSheets")?branchName=' + branchName;
});
</script>
<div class="row-fluid">
<div class="span4" style="margin-top: 15px">
#if (User.IsInRole("Administrator") || User.IsInRole("SuperUser"))
{
<strong>Quick Switch</strong> #Html.DropDownList("BranchQuickChange",ViewBag.CompanyList as SelectList)
}
</div>
Controller:
{
List<WAGBranch> listWagBranch = WAGBranchRepository.GetAllBranches(CompanyEnum.WAG).OrderBy(i => i.BRName).ToList();
List<string> listCompany = new List<string>();
foreach (WAGBranch branch in listWagBranch)
{
listCompany.Add(branch.BRName); // + " - " + branch.Branch);
}
//listCompany.Insert(0, "WAG HEAD OFFICE - WAG");
if ((string)selected == "") selected = null;
ViewBag.CompanyList = new SelectList(listCompany, selected);
}
Model:
[TableNameAttribute("WAGTripHdr")]
public class WAGTripHdr : SQLSelectUpdateInsertHelper
{
public string DebName { get; set; }
}
Waiting for some advices.
That error usually occurs when the collection passed to DropDownListFor is null. As a fallback, the helper tries to find the options in the ViewBag under a member named after the property, i.e. ViewBag.BranchQuickChange. When it fails to find anything usable there, as well, it gives up and you get the exception you reference.
That said, it appears you are in fact setting ViewBag.CompanyList in your action. Additionally, it is being set to a SelectList instance, so casting it back to SelectList in the view as you're doing should materialize the value. The only thing I can think of is that perhaps a different action than the one you've posted here is being loaded. In particular, if you have GET and POST versions of this action, make sure that both set ViewBag.CompanyList. It's possible you only added that line to one and not the other.

Partial view not showing in the view in asp.net mvc4

I have created a view in which I want to show another Partial view. Below is my Code:
Controller
public ActionResult AddToCompare(string id)
{
var lst = db.CompareProduct.Where(p => p.CreatedDate.Year == DateTime.Now.Year && p.CreatedDate.Month == DateTime.Now.Month && p.CreatedDate.Day == DateTime.Now.Day).ToList();
return PartialView(lst);
}
View.cshtml
<p class="compare">
#Ajax.ActionLink("Add To Compare", "AddToCompare", new { id = Model.ProductId }, new AjaxOptions { UpdateTargetId = "CompareList" })
</p>
<div id="CompareList" class="clear">
Compare List
</div>
I have also referenced jquery.unobtrusive-ajax.min.js in my view but when i click on the above link it opens the partial view in new page instead of showing it into the same view.
Am I doing something wrong? Please help me.
Thanks in advance..
Maybe its becouse your js files should be the next format
1 jquery
2 jquery.unobstrusive
3 jquery.unobstrusive-ajax
Thanks for the all the help.
I found another way to show the Partial View. I just add a jquery function and call it on the onClick event. Below is the code if anybody needs.
jQuery function
function getView() {
$('#CompareList').load("#Url.Action("AddToCompare", "Product", new { id = Model.ProductId })");
}
Calling Link
Add To Compare
It worked like a charm !!
Thanks

Can I bind data to data-win-options?

I use the control MicrosoftNSJS.Advertising.AdControl in the ItemTemplate of a ListView.
I would like to bind some datas to the following data-win-options properties : ApplicationId and AdUnitId
The source datas are correctly set and are visible in my item template, I can display them with an h2 + a classic data-win-bind on innerText property
Ads are displayed correctly if I put directly static IDs in html code but these IDs need to be loaded from a config file...
Is it possible ? Thanks
If it's not possible, can I modify directly the item template in the JS code before to be injected in the listview ?
Come to find out this is possible (I was trying to do something similar)
The syntax for the control properties must be prefixed with winControl.
Example (I'm setting the application id here but binding the html element's className and the ad control's adUnitId)
<div id="adItemTemplate" data-win-control="WinJS.Binding.Template">
<div data-win-bind="className:css; winControl.adUnitId: adUnitId"
data-win-control="MicrosoftNSJS.Advertising.AdControl"
data-win-options="{ applicationId: 'd25517cb-12d4-4699-8bdc-52040c712cab'}">
</div>
</div>
I finally found a way to perform this without real binding, by using the itemTemplateSelector function like this :
function itemTemplateSelector(itemPromise)
{
return itemPromise.then(function (item)
{
if (item.type == "ad")
{
var template = _$(".adTemplate").winControl.render(item, null);
// Access to the AdControl through the DOM
var adControl = template._value.childNodes[1].childNodes[1].winControl;
// Set options that are specified in the item
WinJS.UI.setOptions(adControl, { applicationId: item.AdAppId, adUnitId: item.AdUnitId });
return template;
}
else
{
return _$(".itemTemplate").winControl.render(item, null);
}
}
}
I had this problem in ratings:
<div data-win-control="WinJS.UI.Rating" data-win-options="{averageRating: 3.4, onchange: basics.changeRating}"></div>
I bind it via winControl:
<div data-win-control="WinJS.UI.Rating" data-win-bind="winControl.averageRating: myrating" data-win-options="{onchange: basics.changeRating}"></div>
It worked fine.
<div data-win-bind="this['data-list_item_index']:id WinJS.Binding.setAttribute" >

MVC 4 how to add a <div> element conditionally

Want to add a HTML (div) element conditionally. But code exerpt from my Create.cshtml does not work as the parser gets mixed up missing the end-div (the first closing "}" is no code anymore)
#if (setDiv)
{
<div class="#item.DivClass" id="#item.DivId">
}
// More code more HTML
if (setDiv)
{
</div>
}
Anyone an idea how to tackle this problem? Thanks in advance!
Gerard
You have to encapsulate your opening and closing divs in #Html.Raw(). Otherwise razor will not allow this syntax as it does not know that the div that you opened in one if statement is actually closed in another.
#if (setDiv)
{
#Html.Raw("<div class='#item.DivClass' id='#item.DivId'>")
}
// More code more HTML
#if (setDiv)
{
#Html.Raw("</div>")
}
Try this:
#if (setDiv)
{
<div class="#item.DivClass" id="#item.DivId">
}
// More code more HTML
#if (setDiv)
{
#:</div>
}