how to get model values in javascript - javascript

testModel
public class testModel
{
public int ID{get; set;}
public string name{get; set;}
}
cshtml code
#model IEnumerable<testModel>
var lstModel = Model.ToList();
<div id="mainOfferDiv">
#for(int i = 0; i<lstModel.Count(); i++)
{
}
</div
In js file i want to get list of testModel data which is there in cshtml file, I tried with below
js file
var listModel = document.getElementById("mainOfferDiv");
Suppose lstModel contains list of 10data i want to get same in js file
Thank you in advance

You could take your entire server-side model and turn it into a Javascript object by doing the following:
var model = #Html.Raw(Json.Encode(Model));
In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:
var floorplanSettings = #Html.Raw(Json.Encode(Model.FloorPlanSettings));
another way is
Classs property ---
Name = "Raj",
IsAuthenticated = true,
LoginDateTime = DateTime.Now,
Age = 26,
UserIconHTML = "<i class='fa fa-users'></i>"
---------------------------------
js in cshtml
var Name = #Model.Name;
var Age = #Model.Age;
var LoginTime = #Model.LoginDateTime;
var IsAuthenticated = #Model.IsAuthenticated;
var IconHtml = #Model.UserIconHTML;

Related

Alfresco datalist send email on very new item creation

I have applied rule on datalist folder like on each item creation, it should drop an email to respective person.
Below is the script for the same:
function main()
{
var site = siteService.getSite("hardik-test");
var dataListsContainer = site.getContainer("datalists");
var dataLists = dataListsContainer.getChildren();
var fullName, manager,joiningDate;
for(var x=0;x<dataLists.length;x++)
{
var dataList = dataLists[x];
var props = dataList.getProperties();
var title = props["cm:title"];
if(title.equals("Employee"))
{
var dataListItems = dataList.getChildren();
for (var y = 0; y < dataListItems.length; y++)
{
var dataListItem = dataListItems[dataListItems.length-1];
var dataListItemProps = dataListItem.getProperties();
fullName = dataListItemProps["emp:fullName"];
manager = dataListItemProps["emp:manager"];
joiningDate = dataListItemProps["emp:joiningDate"];
}
}
}
// create mail action
var mail = actions.create("mail");
mail.parameters.to = "xyz#xyz.com"; //manager email id should be there
mail.parameters.subject = "Task assigned to you.";
mail.parameters.from = "xyz#xyz.com";
//mail.parameters.template = companyhome.childByNamePath("Data Dictionary/Email Templates/Notify Email Templates/notify_user_email.html.ftl");
mail.parameters.text = "Hi "+manager +"," + "\n A new employee " +fullName +" will be joining our team on "+ joiningDate + "." +
"\n For details, Please click here. \n Regards, \n Administrator" ;
mail.execute(document);
}
script is running every time when we create new item but in the email it's not fetching the latest data we entered.
If we want to use email template, then how can we pass parameter(custom values) to email template?
Want to create link that will redirect to datalist.
This is one of the many times when the Alfresco source can be instructive. If you take a look at the MailActionExecuter class you'll see that it has several parameters defined:
public static final String NAME = "mail";
public static final String PARAM_LOCALE = "locale";
public static final String PARAM_TO = "to";
public static final String PARAM_CC = "cc";
public static final String PARAM_BCC = "bcc";
public static final String PARAM_TO_MANY = "to_many";
public static final String PARAM_SUBJECT = "subject";
public static final String PARAM_SUBJECT_PARAMS = "subjectParams";
public static final String PARAM_TEXT = "text";
public static final String PARAM_HTML = "html";
public static final String PARAM_FROM = "from";
public static final String PARAM_FROM_PERSONAL_NAME = "fromPersonalName";
public static final String PARAM_TEMPLATE = "template";
public static final String PARAM_TEMPLATE_MODEL = "template_model";
public static final String PARAM_IGNORE_SEND_FAILURE = "ignore_send_failure";
public static final String PARAM_SEND_AFTER_COMMIT = "send_after_commit";
One of those is PARAM_TEMPLATE_MODEL which you would set by using "template_model". The "model" in that parameter is what should be catching your eye. It means you can pass in a set of keys and values by using that parameter.
Later, in the source for that class we see where the parameter is read and then used to build the full model that is then passed in to the Freemarker template:
Map<String, Object> suppliedModel = null;
if(ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL) != null)
{
Object m = ruleAction.getParameterValue(PARAM_TEMPLATE_MODEL);
if(m instanceof Map)
{
suppliedModel = (Map<String, Object>)m;
}
else
{
logger.warn("Skipping unsupported email template model parameters of type " + m.getClass().getName() + " : " + m.toString());
}
}
// build the email template model
Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, suppliedModel, fromPerson, toRecipients);
So, if you comment in the reference to the template and you pass in an additional parameter to the action, assuming your template makes use of the items you add to the model, you should see those in the resulting email.
Your code would look something like:
var templateModel = {};
templateModel["fullName"] = fullName;
templateModel["manager"] = manager;
templateModel["joiningDate"] = joiningDate;
mail.parameters.template_model = templateModel;

Store Model as JSON in Hidden input and access it in javascript

How do I store a Model in a hidden input and access it in my javascript function?
I am storing the model in a hidden field as
string defaultFareListJson =
Newtonsoft.Json.JsonConvert.SerializeObject(#Model.DefaultFare);
#Html.Hidden("DefaultFareList", defaultFareListJson);
And in my Javascript function, I am trying to access it as:
function viewDefaultFareSchedule() {
var defaultFareObject = {}
defaultFareObject.Fares = jQuery.parseJSON($('#DefaultFareList').val());
alert(defaultFareObject.Fares[0].facility);
}
My ViewModel is as follows:
public class NavBarCallerViewModel
{
public FareSchedViewModel DefaultFare { get; set; } = new FareSchedViewModel();
}
public class FareSchedViewModel {
public string facility{get;set;}
}
NH
I was able to parse a hidden JSON string("DefaultFareList": converted from Model) as :
var defaultFareString = document.getElementById('DefaultFareList').value;
var defaultFare = JSON.parse(defaultFareString);

How to access object properties in javascript?

I am passing an object(model) in View where I have javascript code written. The object has certain properties that I want to access in javascript in order to create a drop down list from the values of those properties.
Here is my object:
public class TestObject
{
public BuildData ExteriorColor { get; set; }
public BuildData InteriorColor { get; set; }
}
and
public class BuildData
{
public List<ExteriorInteriorData> Data { get; set; }
public bool isInstalled { get; set; }
public BuildData()
{
Data = new List<ExteriorInteriorData>();
}
}
Now in the View I have an object of TestObject through ViewData and I want to populate the values present in List<ExteriorInteriorData> in a select list.
Basically I want to do something like this:
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
$("#Exterior_Color").append($("<option " + (i == 0 ? "selected" : "") + "></option>").val(data.ExteriorColor.Data[i].ColorName + ", " + data.ExteriorColor.Data[i].RgbValue).html(data.ExteriorColor.Data[i].ColorName));
}
So, How do I access the object TestObject present in Viewdata inside of Javascript?
if you are writing JavaScript in same view then you just need to convert your model object in js object using this code.
var jsModel = #Html.Raw(Json.Encode(Model))
if you want in external file then create an html element and set this model in data- field and get this model in js like this
View
<div data-JsObject="#Html.Raw(Json.Encode(Model))" id="JSOBJ"> </div>
JS External file
var list = JSON.parse($("#JSOBJ").data("JsObject"))
I hope it'll work for you.
except of javascript you can use defualt razor helper for create dropdownlist :
#Html.DropDownListFor(model => model.ExteriorColor.Data, new SelectList(Model.ExteriorColor.Data, "Value", "Text"))
repale Value and Text By properties in ExteriorInteriorData
Try this. Use for loop within the tag.
#model [yourproject].Models.TestObject
<select id="Exterior_Color" name="Exterior_Color">
#foreach (var item in this.Model.ExteriorColor)
{
<option value="#item.RgbValue">#item.ColorName</option>
}
</select>
You can simply get selected item from javasrcipt
$("#Exterior_Color").val();

dropdownlist not showing data properly

i have this dropdown list which get the data from db but does not display the data properly n the view
The codes are as follows:
View:
#Html.DropDownListFor(m=> Model.SystemRAteModel.Role, new SelectList(Model.SystemRAteModel.GetRole.Items),"Value","Text")
Model:
public class SystemRolesModel
{
public static RoleProvider Provider { get; internal set; }
public int ID { get; set; }
public String Role { get; set; }
public Boolean Status { get; set; }
public SelectList GetRole { get; set; }
}
Controller
public ActionResult Index()
{
IApplicationLogic app = new ApplicationLogic(session);
RateManagementModel RTM = new RateManagementModel();
var value = app.GetVatValue();
var freight = app.GetFreightValue();
// var systemrolemodel = new SystemRolesModel();
//var currency = new List<SelectList>();
// currency= app.GetListOfRoles();
//IList<string> ERModel = new List<string>();
//foreach (var _currency in currency)
//{
// var curent = _currency.ToString();
// ERModel.Add(curent);
//}
var sysmodel = new SystemRolesModel();
sysmodel.GetRole = getRoleSelectList();
RTM.SystemRAteModel = sysmodel;
ViewData["ViewVatValue"] = value;
//ViewData["ViewCurrency"] = new SelectList(currency);
//ViewBag.LocationList = freight;
ViewData["ViewFreightValue"] = freight;
return View("Index",RTM);
}
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles();
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
IEnumerable<SystemRoles> sortedRoles = roles.OrderBy(d => d.Id);
IList<SystemRoles> _sortedRoles = sortedRoles.ToList();
return new SelectList(_sortedRoles, "Id", "Role");
}
i have tried everything on the net but cant get a hand on it. Please any help will do.OutPut of my System At the moment
You don't need to create a new SelectList again in View, as you are already creating that in controller side and passing it via Model, you should be able to directly use it in View like:
#Html.DropDownListFor(m=> Model.SystemRAteModel.Role,Model.SystemRAteModel.GetRole)
This should populate the dropdown with the values, but it would display same values for all the items for now, as your code is setting hard-coded same values for all properties here:
SystemRoles sr = new SystemRoles();
sr.Id = -1;
sr.Role = "--select role--";
roles.Add(sr);
You would need to change it to have proper values.
Another easy way can be to use the constructor of SelectList this way:
public SelectList getRoleSelectList()
{
IApplicationLogic app = new ApplicationLogic(session);
var roles = app.GetListOfRoles().OrderBy(x=> x.RoleID);
return new SelectList(roles.ToList(), "RoleID", "Role");
}
you will just need to replace RoldID and Role property name with the proerty names you have in the DTO.
Hope it helps.
See this example:
#Html.DropDownList("Name", Model.Select(modelItem => new SelectListItem
{
Text = modelItem.Name,
Value = modelItem.Id.ToString(),
Selected = modelItem.Id == "12314124"
}))

Serialize enum to const JsonNet

I am using Asp MVC 3 application.
I have an Enum:
public enum EmployeesOptions
{
John = 1,
Peter = 2,
Andrew = 3
}
And a MyViewModel class
public class MyViewModel
{
public MyViewModel()
{
Employees = new List<EmployeesOptions>()
{
EmployeesOptions.John,
EmployeesOptions.Peter,
EmployeesOptions.Andrew
};
}
public IEnumerable<EmployeesOptions> Employees { get; set; }
}
My Controller:
public ActionResult Index()
{
var vm = new MyViewModel();
return View(vm);
}
In My Index View:
#model MyViewModel
<script type="text/javascript">
var jsonString = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';
var data = ko.mapping.fromJSON(jsonString);
omega.franchiseInfo = ko.mapping.fromJS(data);
</script>
My serialized data coming from the server looks like this:
Emplyees:[1,2,3]
I want to be like this:
Emplyees:["John","Peter","Andrew"]
What am I missing ?
Update:
var jsonString = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.Converters.StringEnumConverter()))';
This do the job!
If you want this enum type always to be serialized with its string values, you can decorate it with a JsonConverter attribute and the StringEnumConverter class like this:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
[JsonConverter(typeof(StringEnumConverter))]
public enum EmployeesOptions
{
John = 1,
Peter = 2,
Andrew = 3
}
Then you don't need to specify any converter classes in the serializer options anymore.
I tried decorating a List property that holds Enum values with [JsonConverter(typeof(StringEnumConverter))] but understandably that didn't work since it should decorate the Enum type directly.
// Did not work!
[JsonConverter(typeof(StringEnumConverter))]
public List<Assessment.AssessmentFunction> SelectedFunctions { get; set; }
then I did as you suggested and it worked as expected.
var selectedFunctions = #Html.Raw(JsonConvert.SerializeObject(Model.SelectedFunctions,
new StringEnumConverter()))
Instead of Enum int values now I get Enum strings in the JavaScript code inside a Razor .cshtml view. Just what I needed in a specific situation.
Before
var selectedFunctions = #Html.Raw(Json.Encode(Model.SelectedFunctions))
// Output
var selectedFunctions = [3, 3, 2, 2, 2, 3, 2, 2]
After
var selectedFunctions = #Html.Raw(JsonConvert.SerializeObject(Model.SelectedFunctions,
new StringEnumConverter()))
// Output
var selectedFunctions = ["Nurse","Nurse","Doctor","Doctor","Doctor","Nurse","Doctor","Doctor"]
You are returning enums, and by default it will display the enum values. You can modify your model like this.
public class MyViewModel
{
public MyViewModel()
{
Employees = new List<EmployeesOptions>()
{
EmployeesOptions.John.ToString(),
EmployeesOptions.Peter.ToString(),
EmployeesOptions.Andrew.ToString()
};
}
public IEnumerable<EmployeesOptions> Employees { get; set; }
}
By using the .ToString() extension method we can convert enums to the exact thing they are representing to string format.

Categories

Resources