ASP.NET MVC 2 paging Route Problem - asp.net-mvc-2

I get error when paging,
my actions:
ProductList(string country, string city, string town, int? pageNumber)
my Route:
routes.MapRoute(
"ProductList",
"myList/{country}/{city}/{town}/{pageNumber}",
new { controller = "Product", action = "ProductList", country="", city="", town= "", pageNumber = UrlParameter.Optional });
Action Link:
Url.Action("myList","Product", new{ country="Finland",city="",town="",pageNumber=2 })
city = 2 ??
I've found a solution as follows:
Url.Action("myList","Product", new{ country="Finland",city="s",town="n",pageNumber=2 })
http:/myList/Finland/s/n/2
ProductList(string country, string city, string town, int? pageNumber)
{
city== "s" ? city = null;
town == "n" ? town= null;
process...
}
to be http:
/myList/Finland/2
/myList/Finland/Helsinki/3
/myList/Finland/town/7

You cannot skip the parameters in that route. You just can't call http://mylist/2 and expect pageNumber to take value 2. Value in first segment is assigned to the first variable in the route. So 2 is assigned to city variable. You have to make sure all parameters before pageNumber gets a non-null value.

Only the last parameter in your route definition can be optional.

Related

MongoDB query for equal search with $regex

I have an entity
class Data {
string name;
string city;
string street;
string phone;
string email;
}
An api has been written to find Data by each param. This is search api so if a param is provided, it will be used if not then everything has to be queried for that param.
#Query("{'name': ?0,'city': ?1,'street': ?2, 'phone': ?3,'email': ?4}")
Page<IcePack> findDataSearchParams(String name,
String city,
String street,
String phone,
String email);
This only works when all the params are sent in the request. It wont work if any of the params are not sent because it will look for null value in the DB for that param.
I want to query everything for that param if it is not requested like the way it is done in SQL. I tired to use $regex with empty string when something is not sent but regex works like a like search but I want to do equal search
anyway to do this
Filtering out parts of the query depending on the input value is not directly supported. Nevertheless it can be done using #Query the $and and operator and a bit of SpEL.
interface Repo extends CrudRepository<IcePack,...> {
#Query("""
{ $and : [
?#{T(com.example.Repo.QueryUtil).ifPresent([0], 'name')},
?#{T(com.example.Repo.QueryUtil).ifPresent([1], 'city')},
...
]}
""")
Page<IcePack> findDataSearchParams(String name, String city, ...)
class QueryUtil {
public static Document ifPresent(Object value, String property) {
if(value == null) {
return new Document("$expr", true); // always true
}
return new Document(property, value); // eq match
}
}
// ...
}
Instead of addressing the target function via the T(...) Type expression writing an EvaluationContextExtension (see: json spel for details) allows to get rid of repeating the type name over and over again.

Null value for Put Request in RestApi

I'm coding Rest API with .NET Core. I am having a problem. I use Postman for test.
For example; My variable: name, surname, age.
(Normally: ID:1, name: Amet, surname: Asar, age:30)
I'm using Put request.
{
"ID": 1
"name": "Ayhan",
"surname":"Hara"
}
But I don't send "age". So, it's saving null value for age.
Like;
id=1, name=Ayhan, surname=Hara, age=null
How can check null variable? If the age value has not enter, don't change.
[HttpPut("{id}")]
public ActionResult Update(int id, [FromBody]JsonPutDocument<Customer_UserDTO> customer_UserDTO)
{
if (!ModelState.IsValid)
return BadRequest("İstenilen Datalar Düzgün Değil");
var user = unitOfWork.customer_User.GetById(id);
if (user == null)
return NotFound("İlgili müşteri bulunamadı");
var userToPut = mapper.Map<Customer_UserDTO>(user);
customer_UserDTO.ApplyTo(userToPut, ModelState);
mapper.Map(userToPut, user);
unitOfWork.SaveChanges();
return Ok(mapper.Map<Customer_User>(user));
}
You probably want to take a look at [Patch]. Specifically, this blog will help you: https://dotnetcoretutorials.com/2017/11/29/json-patch-asp-net-core/
Your only other real alternative is to manually map the properties based on your own conditions.
Alternatively, it might be a question for the Automapper guys at: https://github.com/AutoMapper/AutoMapper

Entity Framework seeding complex objects?

I am trying to figure out how to seed a complex entity framework code first object. Currently the code I have allows me to insert simple objects but there has to be a way do more complex items, i.e. Address with an AdressType field.
context.AddressTypes.AddOrUpdate(
p => p.Name,
new AddressType { Name = "Original" },
new AddressType { Name = "Shipping" },
new AddressType { Name = "Billing" }
);
context.Addresses.AddOrUpdate(
a => a.Address1,
new Address
{
Address1 = "1234 West Main",
City = "Hannibal",
Region = "MO",
PostalCode = "12345",
Country = "USA",
Type = context.AddressTypes.Where(a=>a.Name=="Original")
});
But while I can "Find" an addresstype by id I can't do a "Where" name equals. Find would work except that I can not guarantee what the id will be with each seed and want to base it on name instead.
Any suggestions on how to do this?
TIA
Solution:
Added a reference System.Linq to the seed class. Then was able to the where clause.

Grails - Query list of items from multiple domains

Working on grails 3 application. My domain structure is defined below:
Job{
Integer id
String title
Date publishedDate
}
JobType{
Integer id
String name
}
JobJobTypeMap{
String jobId
String jobTypeId
}
For example,
**Job**
id title
1 job1
2 job2
**JobType**
id name
1 govt
2 private
**JobJobTypeMap**
jobId jobTypeId
1 1
1 2
2 2
I need to get list of jobs (offset and max attributes and order published date descending) with particular jobType.
Kindly, don't ask me to change the domain structure.
Any suggestions would be appreciated
You are not defining properly the domain classes. You don't have to create the relation class between Job and JobType, Grails will do it automatically on you DB.
Job{
Integer id
String title
Date publishedDate
JobType jobType
}
JobType{
Integer id
String name
}
List<Job> jobs = Job.findAllByJobType(jobTypeInstance, [sort: '', order:'', max: '', offset: ''])
You have to use Grails SQL/HSQL to query the DB.
In controller
def getList() {
def params = [column:"job.title", order:'DESC', offset:0, limit:5]
Sql sql = new Sql(dataSource)
String query = """
SELECT job_job_type_map.job_id jobId, job_job_type_map.job_type_id jobTypeId,
job.title jobTitle, jobType.name jobTypeName
FROM job job, job_type jobType, job_job_type_map job_job_type_map
WHERE job_job_type_map.job_id = job.id
AND job_job_type_map.job_type_id = jobType.id
ORDER BY ${params.column} ${params.order}
LIMIT :limit
OFFSET :offset
"""
List<GroovyRowResult> result = sql.rows(query, params)
result.each {
println "${it.jobId} ${it.jobTypeId} ${it.jobTitle} ${it.jobTypeName}"
}
render template: 'list', model: [jobRows:result]
}
in GSP
<g:each in="${jobRows}" var="job">
"${job.jobId} ${job.jobTypeId} ${job.jobTitle} ${job.jobTypeName}" <br/>
</g:each>
Be careful ORDER BY ${params.column} ${params.order}
There is restriction in using named parameter in some places. You can find here
Enjoy!
If you do not want to change domain structure and do not want to write SQL/HSQL then you can use this approach:
def jobTypeId = JobType.findByName(params.jobTypeName).id
def jobIdList = JobJobTypeMap.findAllByJobTypeId(jobTypeId)?.jobId
def jobList = Job.createCriteria().list(max:max, offset:offset) {
'in'("id", jobIdList)
order("publishedDate", "desc")
}
jobList will give you the list of all jobs with specific job type, max, offset and order by publishedDate.

ActionLink for a Custom MapRoute with two URL Parameters

I have a custom MapRoute
context.MapRoute("participantByGender",
"Admin/Participants/{id}/{gender}",
new {
controller = "Admin",
action = "Participants",
id = UrlParameter.Optional,
gender = UrlParameter.Optional
}
and i need to have a link which specifies both the id and a default gender. I have this one, which works for choosing the id, but how would i alter this to include the id and the gender in the link?
#Html.ActionLink("Participants", "Participants", new { id = item.termId })
Simply use:
#Html.ActionLink("Participants", "Participants", new { id = item.termId,gender=model.property })