Currently I have a Controller named StoreController. There are three Categories : books, movies, and games. How can i make sure that the url's
http://mywebsite.com/store/books,
http://mywebsite.com/store/movies
http://mywebsite.com/store/games
match a single action method. Right now, I am having three separate action methods books(); movies(); games(); doing the same thing, i.e listing the products in them
Did you try like this?
routes.MapRoute(
"Default", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Store", action = "Index", id = UrlParameter.Optional } // Parameter defaults
, null }
)
and you make Controller like
public ActionResult Index(string id)
{
if(id == "books"){
}
else if(id == "movies"){
}
else{// this is null case
}
return Content("hello");// test
}
Related
I'm trying to insert a many-to-many table with web api odata controls.
And I' ve created controls with scaffolding odata controllers with ef.
Everything is great. I can query the user table like this:
GET http://localhost:51875/odata/Users(1)?$expand=Roles
{
"odata.metadata": "http://localhost:51875/odata/$metadata#Users/#Element",
"Roles": [
{
"ID": 20,
"Name": "Admin"
}
],
"ID": 1,
"UserName": "user",
"Password": "pass",
"EnteredDate": "2017-12-07T14:55:22.24",
"LastLoginDate": null,
"Active": true
}
I've inserted the record 'Admin' manually. How can I add a new role for user?
I've tried,
PATCH http://localhost:51875/odata/Users(1)
{
"Roles": [
{
url : "http://localhost:51875/odata/Roles(10)"
}
],
}
it did not work. Can you help me?
Bit late perhaps but there is an answer to this, it is described on: learn.microsoft.com/...
Add the following CreateRef method to your UserController:
[AcceptVerbs("POST", "PUT")]
public IHttpActionResult CreateRef([FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
{
var user = Db.Users
.FirstOrDefault(p => p.Id == key); //Get User by id
if (user == null)
{
return NotFound();
}
switch (navigationProperty)
{
case "Roles":
// You'll have to impement this 'getkey' method somehow.
// You could implement it yourself or take a look on the webpage I linked earlier.
var relatedKey = GetKeyFromUri(link);
var role = Db.Roles
.FirstOrDefault(f => f.Id == relatedKey); //Get Role by id
if (role == null)
{
return NotFound();
}
user.Roles.Add(role);
break;
default:
return StatusCode(HttpStatusCode.NotImplemented);
}
Db.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
Now you can add roles to a user with the following HTTP request:
PUT [...]/api/User(2)/Roles/$ref
Content-Type: application/json
Content-Length: 54
{ "#odata.id": "[...]/api/Role(4)/" }
Personally I don't find this method particularly nice but it is the standard. You could also do this with a custom 'AddRoles' action as you mention in your comment.
How get a user of this class, from a lastName, not from the id.
in my example i use a REST web service.
My class USER.groovy in Grails:
class User {
String firstName
String lastName
String zipcode }
class UrlMappings.groovy
class UrlMappings {
static mappings = {
/user/$id" (controller: "user") {
action = [GET: "show"]
}
}
}
def show in UserController.groovy
def show = {
User user = User.get(params.id)
if (user) {
render user as JSON
} else {
SendNotFoundResponse()
}
}
As I understand, your problem that you don't know how to query domain by other fields that id. For current example you can use:
User.findByFirstName(params.id)
And, please read about GORM querying - http://grails.org/doc/latest/guide/GORM.html#querying
I've defined the following route:
routes.MapRoute(
null,
"foo/{id}/{title}",
new { controller = "Boo", action = "Details" }
);
When I call this method:
Url.Action("Details", "Boo", new { id = article.Id, title = article.Title })
I get the following URL:
http://localhost:57553/foo/1/Some%20text%20Š
I would like to create a new route that will lowercase all characters and replace some of them.
e.g.
http://localhost:57553/foo/1/some-text-s
Rules:
Uppercase -> lowercase
' ' -> '-'
'Š' -> 's'
etc.
Any help would be greatly appreciated!
Seems like a perfect candidate for a custom route:
public class MyRoute : Route
{
public MyRoute(string url, object defaultValues)
: base(url, new RouteValueDictionary(defaultValues), new MvcRouteHandler())
{
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
values = new RouteValueDictionary(values);
var title = values["title"] as string;
if (!string.IsNullOrEmpty(title))
{
values["title"] = SEOify(title);
}
return base.GetVirtualPath(requestContext, values);
}
private string SEOify(string title)
{
throw new NotImplementedException();
}
}
which will be registered like this:
routes.Add(
"myRoute",
new MyRoute(
"foo/{id}/{title}",
new { controller = "Boo", action = "Details" }
)
);
Now all you have to do is to implement your SEO requirements in the SEOify function that I left. By the way you could get some inspiration from the way StackOverflow does it for the question titles.
Ive got a dropdown on one of my views. This dropdown only has for entries. Basically i need to know how to call an action when the dropdown value is changed?
My situation is: Im making a simple inbox page. The dropdown has the filter options: View All, View Invites, View Replies etc..
When the user selects a filter option from the dropdown I want to call to an action to return the new view with the filtered data.
Any ideas? Im guessing it is somehow going to be a script attached to the OnChange of the dropdown, but i wouldnt have a clue what the syntax is or how call MVC action from the script.
Thanks in advance
You need to use javascript for this. Here's an example. Suppose you have the following view model:
public class MyViewModel
{
public IEnumerable<SelectListItem> Values { get; set; }
}
which you would populate in your controller:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Values = new[]
{
new Item { Value = "1", Text = "Item 1" },
new Item { Value = "2", Text = "Item 2" },
new Item { Value = "3", Text = "Item 3" }
}
};
return View(model);
}
}
And then the view which is strongly typed to this model:
<%: Html.DropDownListFor(x => x.SelectedValue,
new SelectList(Model.Values, "Value", "Text"),
new { id = "items" }
)%>
The last part is to register for the change event (using jquery in this example):
$(function () {
// Register for the change event of the drop down
$('#items').change(function () {
// When the value changes, get send an AJAX request to the
// Filter action passing the selected value and update the
// contents of some result div with the partial html returned
// by the controller action
$('#result').load('<%: Url.Action("filter") %>',
{ selectedValue: $(this).val() }
);
});
});
I'm trying to create a route to a specific controller/action which needs to accept optional querystring parameters.
the urls i'd like to accept are:
/Products/ProductsListJson
/Products/ProductsListJson?productTypeId=1
/Products/ProductsListJson?productTypeId=1&brandId=2
/Products/ProductsListJson?productTypeId=1&brandId=2&year=2010
I have an action like this:
public JsonResult ProductsListJson(int productTypeId, int brandId, int year)
And a route like this:
routes.MapRoute(
null, "Products/ProductsListJson",
new { controller = "Products", action = "ProductsListJson", productTypeId = 0, brandId = 0, year = 0 }
);
I assumed that the action "ProductsListJson" would simply see the querystring urls and map them to the appropriate arguments however this is not happening.
Anyone know how this could be achived?
You don't need to specify their values in the route if those parameters are passed in the query string:
routes.MapRoute(
null, "Products/ProductsListJson",
new { controller = "Products", action = "ProductsListJson" }
);
and your action:
public ActionResult ProductsListJson(int? productTypeId, int? brandId, int? year)
{
...
}
but you probably don't need a specific route for this as the default route will handle it just fine:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);