I have a listbox that I am populating using a foreach. (Long explanation of why I need to do this.)
I need to escape the string because fname and lname can contain special characters, like ' or ".
foreach (var cust in item.Customers)
{
var custString = string.Format("{0}%#%{1}%#%{2}", cust.CustID, cust.LName, cust.FName);
<option value="#custString">#cust.DisplayName</option>
}
Is there any way to do a javascript escape of custString right after setting the value? Or is there there a preferred C# way of escaping that will work well with javascript's unescape, which I am using to unescape these chars.
That's what the AttributeEncode helper does:
<option value="#Html.AttributeEncode(custString)">#cust.DisplayName</option>
But hey, what are you doing? foreach loop to generate a dropdown list????
Try the Html.DropDownListFor helper and stop the bleeding inside your view before its too late. This helper does what its name suggests. And takes care of encoding and escaping and whatever.
So simply define a view model:
public class MyViewModel
{
public string CustomerId { get; set; }
public IEnumerable<SelectListItem> Customers { get; set; }
}
then go ahead and have your controller action populate and pass this view model to the view:
public ActionResult Index()
{
IEnumerable<Customer> customers = ... fetch the domain model from your DAL or something
// map to a view model:
var viewModel = new MyViewModel
{
Customers = customers.Select(x => new SelectListItem
{
Value = x.CustID,
Text = string.Format("{0}%#%{1}%#%{2}", x.CustID, x.LName, x.FName)
})
};
// pass the view model to the view:
return View(viewModel);
}
and inside the view, use the DropDownListFor helper when you need to generate a dropdown list:
#Html.DropDownListFor(x => x.CustomerId, Model.Customers)
Related
I'm new to spring boot development. I have to put my json object inside my model object and send it to view. I've used jackson library's ObjectMapper class to convert the object into String.
My controller snippet is
#GetMapping("/show-employee")
public String showEmployee(Model model) {
ObjectMapper objectMapper = new ObjectMapper();
String empString = objectMapper.writeValueAsString(new Employee("santhosh", "kumar", "example#gmail.com"))
model.addAttribute("employee", empString);
return "employees/employee-display";
}
And my model class is
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotBlank
#Size(min = 3, max = 20)
private String firstName;
#NotBlank
#Size(min = 3, max = 20)
private String lastName;
#Email(message = "Please enter a valid email id")
private String email;
// constructors, getters and setters
On the view side, I have thymeleaf code as below to access the JSON object
<script>
var employeesJsonStr = "[[${employee}]]";
console.log(employeesJsonStr);
</script>
But on the console window, I end up with this...
{"id":0,"firstName":"santhosh","lastName":"kumar","email":"example#gmail.com","projects":null}
How can pass the JSON String to front end so that I can access that using Javascript without having to do html decoding.
I understand you are converting JSON object as string and setting it up inside a model. This is obviously produce String in the front end instead what you could directly send the model object in the response. It will produce JSON data at the end anyway.
#GetMapping("/show-employee" , produces = MediaType.APPLICATION_JSON_VALUE)
public List<Employee> showEmployee(Model model) {
Employee emp = new Employee("santhosh", "kumar", "example#gmail.com"))
model.addAttribute("employee", emp);
return "employees/employee-display";
}
I've been trying to get ng-table(angular directive) work with a web api (ASP.NET MVC). I can load and page the data but the sorting or filtering won't work.
The weird thing is that the sorting or filtering will look like this in the URL:
http://localhost:46278/api/rating?count=10&filter%5Brating.name%5D=fs&page=1&sorting%5Brating.description%5D=asc
If you would "format" it, it would look like this:
filter[rating.name] = fs
sorting[rating.description] = asc
I tried to get them with a string array or a dictionary (KeyValuePair)
But I can't get the values. So I can never filter or sort the data.
I hope you can give me some advice! I appreciate your help!
I wrote a helper class to deal with this. The URL isn't formatted in a way WebAPI expects, so couldn't get the ModelBinder to parse it automatically.
From your controller, call the helpers and provide the entire URL:
// Parse sortings
var sortings = TableHelpers.ParseSortings(Request.RequestUri).ToList();
// Parse filters
var filters = TableHelpers.ParseFilters(Request.RequestUri).ToList();
And the helper class
public static class TableHelpers
{
public static IEnumerable<TableSorting> ParseSortings(Uri requestUri)
{
var regex = new Regex("sorting%5B(.+?)%5D=(asc|desc)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableSorting {Field = match.Groups[1].Value, Order = match.Groups[2].Value};
}
public static IEnumerable<TableFilter> ParseFilters(Uri requestUri)
{
var regex = new Regex("filter%5B(.+?)%5D=(.+?)(?:&|\\z)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableFilter {Field = match.Groups[1].Value, Value = match.Groups[2].Value};
}
}
public class TableSorting
{
public string Field { get; set; }
public string Order { get; set; }
}
public class TableFilter
{
public string Field { get; set; }
public string Value { get; set; }
}
are you asking about directive syntax or your api?
in ng-table directive, insert in <td> tag sorting or/and filtering attrs, like:
<td width="10%" data-title="'NUM'|translate" filter="{ 'num': 'text' }" sortable="'num'"><span>{{item.num}}</span></td>
I'm using asp.net MVC4 for web app development.
I would like to traverse a list of objects from a ViewModel.
Below is the class of the object:
public class User
{
public int Id {get; set;}
public string Name {get; set;}
public string Address {get; set;}
public string Department {get; set;}
}
Below is my ViewModel class:
public class UserViewModel
{
public List<User> AllUsers {get; set;}
public bool IsDeleted {get; set;}
}
As seen in the UserViewModel class, I have a list of objects of type User. Now i would like to iterate through each of the user object in AllUsers list using Jquery and fetch data from them.
In order to do so, I tried doing something like the following:
$(#Model.AllUsers).each( function(){ .... });
I have tried different combination using the above approach, but couldn't succeed. Can anyone suggest a solution for the same.
Thanks in advance.
Assign your collection to a javascript variable using
var users = #Html.Raw(Json.Encode(Model.AllUsers))
which you can then iterate over
$.each(users, function(index, item) {
// access the properties of each user
var id = item.Id;
var name = item.Name;
....
});
<script type="text/javascript">
var UsersList = #Html.Raw(Json.Encode(Model.AllUsers))
for (var i = 0; i < UsersList.length; i++) {
alert(UsersList[i].Id);
alert(UsersList[i].Name);
}
</script>
JavaScript generally is unhappy with razor components although if the above is part of an CSHTML file it will work.
The other approaches are:
Display the collection using razor #foreach ...
Pass the collection as a parameter from you webpage into a JavaScript function on some event
How are you calling this function and what does it do?
In My Case, I fixed by this way :
#for(int i=0;i<Model.AllUsers.Count;i++)
{
#: var name = '#Html.Raw(#Model.AllUsers[i].Name)';
#:alert(name);
}
I have a JObject from JSON.NET with the following:
var jOBject = {"schedule.ID" : 1, "schedule.Name" : "NameSchedule"}
The above is what I get from using Javascript to return the ID's and values of textboxes in the MVC Form in my View.
In my controller using C#, I would like to convert it into a Schedule Object that has the following Properties:
public class Schedule {
public int ID {get;set;}
public string Name {get;set;}
}
I cannot do a
Schedule sched = jsonObject.toObject<Schedule>();
because the names are slightly different as the properties on the Jobject is prepended with 'schedule'.
Is there a query or a way to do the conversion that allows me to remove the 'schedule' in the jsonObject such that I can do the simple conversion in one line?
One simple way to get it working is to use the JsonProperty attribute to specify what JSON key you want to map to a certain C# property:
public class Schedule
{
[JsonProperty("schedule.ID")]
public int ID {get;set;}
[JsonProperty("schedule.Name")]
public string Name {get;set;}
}
Then you can just use JsonConvert.DeserializeObject to deserialize your JSON into a Schedule instance:
var schedule = JsonConvert.DeserializeObject<Schedule>(json);
Example: https://dotnetfiddle.net/Nml9be
To use different key names in the JSON, you can decorate your C# class with DataContract and DataMember attributes.
[DataContract]
public class Schedule {
[DataMember("schedule.ID")]
public int ID { get; set; }
[DataMember("schedule.Name")]
public string Name { get; set; }
}
JObject scheduleObj={schedule:{"ID" : 1, "Name" : "NameSchedule"}}
JsonSerializer seria = new JsonSerializer();
Schedule oSchedule = new Schedule();
if (ScheduleObj["Schedule"] != null)
{
oSchedule = (Schedule)seria.Deserialize(new JTokenReader(ScheduleObj["Schedule"]), typeof(Schedule));
}
Here is the JSON that I want to deserialize into Dictionary using native Javascript support.
string data = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}";
But when I attempt to deserialize using below code
Dictionary values = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize>(data);
It gives me an error stating
"Type 'System.String' is not supported for deserialization of an array"
I am using .Net Framework 3.5. Please help me getting this done.
i guess you can not convert that to a dictionary directly... i think deserializer needs a corresponding type, with intelligible property names with type,
i think you can convert to a type, then generate your dictionary, something like:
public class MyClass
{
public List<bool> Symptom { get; set; }
public List<bool> Action { get; set; }
public bool AllArea { get; set; }
public Dictionary<string, List<bool>> getDic()
{
// this is for example, and many many different may be implement
// maybe some `reflection` for add property dynamically or ...
var oDic = new Dictionary<string, List<bool>>();
oDic.Add("Symptom", this.Symptom);
oDic.Add("Action", this.Action);
oDic.Add("AllArea", new List<bool>() { AllArea });
return oDic;
}
}
then:
string data = "{\"Symptom\":[true,true,true],\"Action\":[true,true],\"AllArea\":true}";
System.Web.Script.Serialization.JavaScriptSerializer aa = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = aa.Deserialize<MyClass>(data);
var dic = o.getDic();
anyhow, it was a good question