Angular ng If not working with razor syntax - asp.net-mvc

I am using Angular Js with Razor.
#{
var pageMode = (string) ViewBag.PageMode;
}
<div ng-if="#pageMode == 'answer'">
<h2>Greetings</h2>
</div>
Value is in ViewBag.PageMode is "answer", still the ng if does not render. i.e "Greetings" message does not work.
What am I doing wrong here... ?

you cant use var pageMode variable inside directives like ng-if. you need to use $scope variable.
so, simplest thing u can do is,
#{
var pageMode = (string) ViewBag.PageMode;
}
<input type="hidden" ng-model="pageMode" ng-init="pageMode = '#pageMode'">
<div ng-if="pageMode == 'answer'">

Related

How to pass dropdown list selected value in knockout function?

I have to pass the dropdown selected value in knockout function. I have crated the razor syntax for that:
<div class="row">
#Html.LabelFor(m => m.FilterByType, htmlAttributes: new { #class = "label" })
#Html.DropDownListFor(m => m.FilterByType, new SelectList(Model.aspNetUser, "FilterByType", "FilterByName"), new { #class = "selectBox", #id = "aspnetUsersType", #data_bind = "event: {change: getData(0,'','',size,index,'')}" })
<input type="hidden" id="filterByType" name="filterByType" value="">
</div>
Following is my knockout function:
self.getData = function (filterbytype, fromdaterange, todaterange, pageSize, page, searchText) {"some task"}
How do I pass the selected value in the getData? Right now I am passing 0 as a filterbytype.
The objects can be passed from server to client using JSON, and binded to a property of type observableArray. Then bind this property to a html element using foreach binding. You can see an example here:
http://knockoutjs.com/documentation/foreach-binding.html
Suppose are using this following code in ur HTML
<select data-bind="options: operations, value: self.selectedOperation">
Make sure that You must be using these variables as ko.observable() type
so ur JS code will look like this
var self = this;
self.selectedOperation = ko.observable("Option1"); // with self u can use more variables and here selectedOperation will be containing the choosen value you want and you can pass it wherever u want
var operations = ko.observableArray(["Option1", "Option2", "option3", "Opt4"]); // dropdown List
Now its up to you how you are going to use that variable..

Checkbox not working in mvc3

I have dynamic check box in my view. But its not working fine its always getting checked
here is my code:
<input type="checkbox" onclick = "InActiveUser('#item.UserId')" id = "#item.UserId" checked="#(item.IsActive == false ? false : true)" />
Please help thanks.
Checked attribute doesn't take true or false as a value. The sole presence of this attribute makes it checked. You have to remove this attribute if you want element to remain unchecked.
Read more in this answer
You have to do it as follows:
<input type="checkbox" onclick = "InActiveUser('#item.UserId')"
id = "#item.UserId" checked="#item.IsActive" />
As Patryk said - you need to change the way the checked attribute is added. Something like this:
<input type="checkbox" onclick = "InActiveUser('#item.UserId')" id = "#item.UserId" #(item.IsActive ? "checked" : "") />
Try that.
Try something like this:
#{
if (ViewBag.IsActive)
{
<input type="checkbox" id="#item.UserId" checked onclick = "InActiveUser('#item.UserId')"/>
}
else
{
<input type="checkbox" id="#item.UserId" onclick = "InActiveUser('#item.UserId')"/>
}
}
Approach - 1
#if(item.IsActive)
{
<input type="checkbox" onclick = "InActiveUser('#item.UserId')"
id = "#item.UserId" checked="checked" />
}
else
{
<input type="checkbox" onclick = "InActiveUser('#item.UserId')"
id = "#item.UserId"/>
}
Approach - 2
You can use below code.
$("input[type='checkbox']").prop('checked', true); // Checked
$("input[type='checkbox']").prop('checked', false); // Un-Checked
If you pay attention to the above code, prop function is used to set the attribute value. You can use JQuery - 1.6 version. Now based upon your condition, you can write Razor code in the JavaScript section like below..
<script type="text/javascript">
$(document).ready(function () { //Some Razor code in JQuery
var status = "#status" == "True" ? true : false;
$("input[type='checkbox']").prop('checked', status);
});
</script>
Server side sample code in View.cshtml
#{
var status = false;
}
Approach - 3
JQuery
<script type="text/javascript">
$(document).ready(function () { //Some Razor code in JQuery
var status = "#status" == "True" ? true : false;
if (!status)
$("input[type='checkbox']").removeAttr('checked');
else
$("input[type='checkbox']").attr('checked', true);
});
</script>
Server side code in cshtml
#{
var status = true;
}
If you pay attention to the above JQuery code, I am removing the checked attribute using the removeAttr in case status value is false and setting it to true using the attr function when status is true.

Adding inline conditional statements in an MVC View

I'm trying to dynamically add a class to a div in an MVC View; in this case error. I find myself creating a Razor If-Else block which means my view has lots of duplicated code. I have tried a few differant Razor scenario's but can't find a reasonable way to conditionally append new classes. Can anyone suggest an approach that avoids duplicating code and keeps View decisions in the View.
#if (ViewData.ModelState["Title"] != null && ViewData.ModelState["Title"].Errors.Any())
{
<div class="select error">
#Html.DropDownListWithTooltipFor(m => m.Title, Model.Titles, new { required = string.Empty, #class = "sel" })
</div>
}
else
{
<div class="select">
#Html.DropDownListWithTooltipFor(m => m.Title, Model.Titles, new { required = string.Empty, #class = "sel" })
</div>
}
Try this:
<div #(condition ? "class=select error" : "class = select">
</div>
Razor will add the quotes for you (class = "select error"). This should work in MVC3.
Also, take a look at: Conditional HTML Attributes using Razor MVC3 and MVC3 - Conditionally add id element with Razor (actually pretty much duplicates)
Note the answer of Erik Porter: If you can do it with MVC4, then there's a more elegant way:
<div class="#yourClass" />

YUI 3 html templating

Is there any way to create HTML markup in YUI like:
<div id={DivId}>
<p class={pClass}>
<span class={spanClass}> {Content} </span>
</p>
</div>
If I understand your question correctly, Y.substitute might be worth looking at.
If you haven't seen it, I'd recommend watching through the YUI 3 Sugar video at the YUI theater. Jump to 22:27 for more on Y.substitute.
I did the same thing.... Here is what I used.
var resultFormatTemplate =
'<div class="result">{first_name}, {last_name}</div>';
function resultFormat(query, results) {
return Y.Array.map(results, function (result) {
var rep = result.raw;
return Y.Lang.sub(resultFormatTemplate, {
first_name : rep['First Name'],
last_name : rep['Last Name']
});
});
};
In the Y.one tag I used resultFormatter : resultFormat to call the function.

Problem binding action parameters using FCKeditor, AJAX and ASP.NET MVC

I have a simple ASP.Net MVC View which contains an FCKeditor text box (created using FCKeditor's Javascript ReplaceTextArea() function). These are included within an Ajax.BeginForm helper:
<% using (Ajax.BeginForm("AddText", "Letters",
new AjaxOptions() { UpdateTargetId = "addTextResult" }))
{%>
<div>
<input type="submit" value="Save" />
</div>
<div>
<%=Html.TextArea("testBox", "Content", new { #name = "testBox" })%>
<script type=""text/javascript"">
window.onload = function()
{
var oFCKeditor = new FCKeditor('testBox') ;
var sBasePath = '<%= Url.Content("~/Content/FCKeditor/") %>';
oFCKeditor.BasePath = sBasePath;
oFCKeditor.ToolbarSet = "Basic";
oFCKeditor.Height = 400;
oFCKeditor.ReplaceTextarea() ;
}
</script>
<div id="addTextResult">
</div>
<%} %>
The controller action hanlding this is:
[ValidateInput(false)]
public ActionResult AddText(string testBox)
{
return Content(testBox);
}
Upon initial submission of the Ajax Form the testBox string in the AddText action is always "Content", whatever the contents of the FCKeditor have been changed to. If the Ajax form is submitted again a second time (without further changes) the testBox paramater correctly contains the actual contents of the FCKeditor.
If I use a Html.TextArea without replacing with FCKeditor it works correctly, and if I use a standard Post form submit inplace of AJAX all works as expected.
Am I doing something wrong?
If not is there a suitable/straight-forward workaround for this problem?
The problem is unrelated to MVC but caused by using FCKeditor in conjunction with AJAX. To fix in the code above I added the following to the submit button's onclick event:
<input type="submit" value="Save" onclick="FCKeditorAPI.GetInstance('TestBox').UpdateLinkedField();" />
For more information see here.

Resources