LayfieldK
LayfieldK

Reputation: 1136

How can I make my index action return a filtered list without adding a query string parameter?

I am just starting out with MVC.NET 5, and I have a picture in my head of what I want to achieve, but I don't have a good idea on how to get there.

Given the following models:

I'd like to be able to go to /Character or /Character/Create and give the controller the necessary info to automatically handle the World part of my request. For example, if I click a link from the world page to go to /Character, I'd like for the controller to somehow know that I want to show only characters belonging to a specific world. And if I click a link to go to /Character/Create, I'd like for it to know that I want to create a character that will belong to a specific world without requiring the user to specify that on the form.

I know that I can pass the World's ID via the query string like /Character?WorldId=xxxx, but I plan on having a complex relational set of models, and the query string will get very ugly very fast.

What is the preferred method of transferring data like this without showing it to the user like in the query string?

Upvotes: 0

Views: 36

Answers (2)

Will Ray
Will Ray

Reputation: 10889

What is the preferred method of transferring data like this without showing it to the user like in the query string?

Well, honestly that would be through a POST request. POST information is put into the header (as opposed to the querystring).

To do this, you would change:

<a href="/Character/?WorldID=1">Click Me</a>

to:

<form action="/Character" method="POST">
    <input type="hidden" name="WorldID" value="1">
    <input type="submit" value="Click Me">
</form>

I know that I can pass the World's ID via the query string like /Character?WorldId=xxxx, but I plan on having a complex relational set of models, and the query string will get very ugly very fast.

I wouldn't make your life more complicated just to make a query string look nicer. Take a look at the URL's you see today as you navigate around. We've got ugly query strings everywhere.

Upvotes: 1

Gerry
Gerry

Reputation: 245

Your controller should be like these: I dont know if you´re using Entity Frameworks but I assume it

private EfDatabase db = new EfDatabase();
//Get Action to call list that you have stored in your database
[HttpGet]
public ActionResult Index(){
var model = db.WorldList.ToList();
return View(model);
}


 [HttpGet]
public ActionResult Create(){
 return View();
}
//World create action
[HttpPost]
public ActionResult Create(World world){
  db.Entry(world).State = EntityState.Add;
  db.SaveChanges();
  return View(); 
}

And you can assume what is next with edit and more controllers you want

Note: I don´t test it yet, I coded it directly here

Hope it helps!

Upvotes: 0

Related Questions