I'm trying to create a mvc application. I have a project controller, actions are below
[AllowAnonymous]
[HttpGet]
public ActionResult Index()
{
//TODO: Browse
return View();
}
[AllowAnonymous]
[HttpGet]
public ActionResult Index(long projectId)
{
using (var entity = new dixraContext())
{
var project = entity.Projects.FirstOrDefault(m => m.Id == projectId);
if (project == null)
return RedirectToAction("NotFound", "Error");
else
return RedirectToAction("Index", project.UrlName);
}
}
[AllowAnonymous]
[HttpGet]
public ActionResult Index(string projectName)
{
using (var entity = new dixraContext())
{
var project = entity.Projects.Where(m => m.Name == projectName);
return View(project);
}
}
I want to show URL's like
example.com/Project/ProjectName
But when i enter url as
example.com/Project/1
Got Error.
An error occurred while processing your request
. as response. When i enter example.com/Project/Index/1 i go into first action.
I also want to resolve project from id and redirect to usual Project/ProjectName url.
Looks like you've got conflicting routes. One way to solve this while leaving your three possible inputs would be checking your input parameter.
Also, your RedirectToAction has a string as its second parameter - that overload of RedirectToAction treats the second parameter as the controller name, not the route object:
Assuming your routes file looks ok:
routes.MapRoute(
name: "Project",
url: "Project/{projectName}",
defaults: new { controller = "Project", action = "Index" }
);
Your controller action might be:
[AllowAnonymous]
[HttpGet]
public ActionResult Index(string projectName)
{
if (string.IsNullOrWhiteSpace(projectName))
{
// return your empty view
}
int projectId;
if (int.TryParse(projectName, out projectId))
{
projectName = GetProjectNameFromDatabase(projectId);
return RedirectToAction("Index", new { projectName });
}
// return your view with your model
}
There may be a better way, but this will work.
Related
I wanna force the Route with .html and a 32 length id.
For example, here is the URL:
https://localhost:44331/Re/test.html?id=12345678901234567890123456789012
I want it when there is no id parameter in the URL or the length of id is not 32, it returns 404 status code.
Here is the controller:
namespace V.Controllers
{
[Route("Re/")]
public class ReController : Controller
{
[Route("test.html{id:length(32)}")]
public IActionResult test(string id)
{
return View();
}
}
}
After I ran the code, it always reports 404 status code.
What's wrong with my route?
I don't think you can specify query string parameters in the route. Try validating the id in the action, or if you can change the route, add it as an additional segment.
[Route("Re/")]
public class ReController : Controller
{
[Route("test.html")]
public IActionResult test(string id)
{
if (id == null || id.Length != 32)
return NotFound();
return Json(new {id= id});
}
[Route("test2.html/{id:length(32)}")]
public IActionResult test2(string id)
{
return Json(new {id= id});
}
}
See: Microsoft Docs
So I have a controller and I can seem to understand how to pass a parameter to my ActionResult method.
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{name}/{id}",
defaults: new { controller = "Project", name = "Search", id = UrlParameter.Optional }
);
This is my route. Now in my controller i've created a method
[HttpGet]
public ActionResult Search()
{
return View();
}
[HttpPost]
public ActionResult Search(int Id)
{
ViewBag.iD = Id;
return View();
}
And in my view
<body>
<div>
ASDF + #ViewBag.iD
</div>
</body>
How can I pass a value to my iD parameter from Search Action? It seems whatever I call
http://localhost:52992/Project/Search/id=2
or http://localhost:52992/Project/Search/1
Both method go into the Search() method, none goes to Search(int iD).
What Am I missing?
A link in your view (or a form with FormMethod.Get or entering a url in the address bar) makes a GET call, not a POST, so your method should be
[HttpGet]
public ActionResult Search(int ID)
{
// do something based on the value of ID
ViewBag.iD = ID;
return View();
}
and delete the [HttpPost] method.
You have to pass value from the HttpGet 'SearchAction' method. if you pass from it, then only the value will be shown in the view
[HttpGet]
public ActionResult Search()
{
ViewBag.iD = your Id value here;
return View();
}
on intial load the get method will be called, on submission only the 'post' method will be call.
hope this helps.
On your view
<a href='#Url.Action("ActionName", "ControllerName", new { id= 10})'>...</a>
OR
#{
int id = 10
}
...
On Your Action
Public ActionResult Search(int id)
{
Viewbag.Id = id;
return view();
}
Action is by default on [HTTPGET] you wont have to mention it
In my application I am creating a record in one view & displaying it in other view.
bellow are controller actions
[HttpPost]
public ActionResult Create(Domain.Entities.Survey survey)
{
ISurveyRepository surveyRepository = new DbSurveyRepository();
surveyRepository.CreateSurvey(survey);
TempData.Add("surveyID",survey.ID);
return RedirectToAction("SingleSurvey");
}
public ActionResult SingleSurvey()
{
if (TempData["surveyID"] != null)
{
ISurveyRepository surveyRepository = new DbSurveyRepository();
Domain.Entities.Survey survey = surveyRepository.GetBySurveyID((int) TempData["surveyID"]);
return View(survey);
}
return View();
}
There are two views
1. Create
2. SingleSurvey
Now when I return view "SingleSurvey" from action "SingleSurvey" the URL displayed on browser is http://localhost:49611/SingleSurvey.
But I want to change this URL. What I want is http://localhost:49611/SingleSurvey/{my record id}/{my record title}
Is there any way to do this ?
In your route config file add the following route:
routes.MapRoute(
"SingleSurvey",
"{controller}/{action}/{id}/{title}",
new { controller = "Survey", action = "SingleSurvey", id = UrlParameter.Optional, title = UrlParameter.Optional }
);
Then update the create action to pass the ID and title as part of the route values:
[HttpPost]
public ActionResult Create(Domain.Entities.Survey survey)
{
ISurveyRepository surveyRepository = new DbSurveyRepository();
surveyRepository.CreateSurvey(survey);
TempData.Add("surveyID",survey.ID);
return RedirectToAction("SingleSurvey", new { id = survey.Id, title = survey.Title );
}
In additon, rather than using the TempData to pass the ID it is better to simply read the ID from the URL. To do this, update the SingleSurvey action to take in the ID as a parameter:
public ActionResult SingleSurvey(int? id)
{
if (id != null)
{
ISurveyRepository surveyRepository = new DbSurveyRepository();
Domain.Entities.Survey survey = surveyRepository.GetBySurveyID(id.Value);
return View(survey);
}
return View();
}
The MVC framework automatically binds the id parameter defined in the route to the id parameter on the action method. If you need to use the title in the SingleSurvey action you can also add it as an extra parameter.
Add 2 nullable parameters to the get method
public ActionResult SingleSurvey(int? id, string title)
{
// if id is not null, get the survey based on id
return View(survey);
}
then in the post method, redirect with the parameters
[HttpPost]
public ActionResult Create(Domain.Entities.Survey survey)
{
ISurveyRepository surveyRepository = new DbSurveyRepository();
surveyRepository.CreateSurvey(survey);
return RedirectToAction("SingleSurvey", new { id= survey.ID, title = survey.Title });
}
You might also want want to define a route so that the url is .../SingleSurvey/someID/someTitle rather than .../SingleSurvey?id=someID&title=someTitle
Side note: Its better performance to initialize a new instance of Survey and use return View(survey); rather than return View() in the case where you are creating a new survey
It seems simple like in ASP.NET MVC but I can't figure out how to map an URI with a string parameter to an action on my controller. So I have three actions in my controller as below:
//GET: api/Societe
public IEnumerable<Societe> GetSociete()
{
List<Societe> listeSociete = Librairie.Societes.getAllSociete();
return listeSociete.ToList();
}
//GET: api/Societe/id
[ResponseType(typeof(Societe))]
public IHttpActionResult GetSociete(int id)
{
Societe societeRecherchee = Librairie.Societes.getSociete(id);
if (societeRecherchee == null)
{
return NotFound();
}
else
{
return Ok(societeRecherchee);
}
}
public IHttpActionResult GetSocieteByLibelle(string name)
{
Societe societeRecherchee = new Societe();
if (!string.IsNullOrWhiteSpace(name))
{
societeRecherchee = Librairie.Societes.getSocieteByLibelle(name);
if (societeRecherchee == null)
{
return NotFound();
}
}
return Ok(societeRecherchee);
}
So I would like to map an URI with the action:
GetSocieteByLibelle(string name)
My route configuration is the default one for Wep API project. May someone explain me how to map an URI to that action ? Thanks in advance !
Looks like the two routes are resulting in the same method call being invoked. Try putting a [Route] attribute on one of them as follows:
[Route("api/Societe/libelle/{name}")]
public IHttpActionResult GetSocieteByLibelle(string name)
{
}
Note that the default /api/Societe/{id} should still hit your first Action.
Im passing the URL like "http://localhost:6384/Name/4:" But this is get an error.
Controller Method :
//
// GET: /Name/5
public string SetName(int id)
{
return "You entered: " + id;
}
Error:
Server Error in '/' Application.
HTTP Error 400 - Bad Request.
Version Information: ASP.NET Development Server 10.0.0.0
Please Help Me!!!
Verify following steps,
1) In global.axas verify the default root as follows,
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
2) Mention controller name in the url , if you controller and action is as follows
public class HomeController : Controller
{
public ActionResult SetName(int id)
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
then url will be ,
http://localhost:6384/Home/SetName/4
You should try this:
public ActionResult SetName(int id) {
return Content("You entered: " id);
}
Sorry, it was easier than that. You're entering the URL incorrect. You have not specified the controller name.
http://localhost:6384/CONTROLLERNAME/SetName/4
In this error message.
HTTP Status 400 Bad Request - Bad Syntax
Possibly, because the Action Result cannot found or not exist.
This is wrong action method:
// GET: /Name/5
public string SetName(int id)
{
return "You entered: " + id;
}
I will correct your action method:
[HttpGet]
public ActionResult Setname(int id)
{
ViewBag.Result = "You entered: " + id;
return View();
}