I want to add posts to threads in my forum project, but to do so I need to pass a parameter with thread ID, so after creating post it will redirect me back to that specific thread, but the problem is that I have no idea how to pass that parameter...
Here is my Create() code:
// GET: /Posts/Create
public ActionResult Create(int id)
{
ViewBag.ThreadId = new SelectList(db.Albums, "ThreadId", "Title");
ViewBag.IdOfThread = id;
return View();
}
//
// POST: /Posts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Posts posts)
{
if (ModelState.IsValid)
{
db.Posts.Add(posts);
db.SaveChanges();
return RedirectToAction("Index", new { **id = 5** });
}
ViewBag.ThreadId = new SelectList(db.Albums, "ThreadId", "Title", posts.ThreadId);
//ViewBag.IdOfThread = id;
return View(posts);
}
When I strongly type number id = 5 it works as intended, so how can I make ActionResult Create(Posts posts) see my ViewBoxes from Create View? Or maybe there is some better way to do that without using ViewBoxes?
Through the glory of EF when you add a model to the Entity and call SaveChanges() it will automatically put the ID back into the model.
if (ModelState.IsValid)
{
db.Posts.Add(posts);
db.SaveChanges();
// Replace Id with whatever your auto increment PK is.
return RedirectToAction("Index", new { id = posts.Id });
}
Related
I am implementing CRUD operations using EF7 and storedprocudures in asp.net core web api project. I have finished implementing the get methods and left with the insert method. I am using Postman to test the web methods. I have written the implementation for Create but unable the post the information via postman isn't hitting the Create web method in the controller. Could somebody let me know what the problem could be. The route of the get and post is the same except the method signature is different.
Controller
public class MoviesController : Controller
{
private readonly IMoviesRepository _moviesRepository;
public MoviesController(IMoviesRepository moviesRepository)
{
_moviesRepository = moviesRepository;
}
[HttpGet]
[Route("api/Movies")]
public async Task<IActionResult> GetMovies()
{
var movies = await _moviesRepository.GetMovies();
var results = Mapper.Map<IEnumerable<MoviesDto>>(movies);
return Ok(results);
}
[HttpGet]
[Route("api/Movies/{ID}")]
public async Task<IActionResult> GetMovie(int ID)
{
var movie = await _moviesRepository.GetMovie(ID);
var results = Mapper.Map<IEnumerable<MoviesDto>>(movie);
return Ok(results);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("api/Movies")]
public IActionResult CreateMovie([FromBody] MoviesDto movies)
{
if (movies == null)
{
return BadRequest();
}
// Check if movie exists
var movie = _moviesRepository.GetMovie(movies.MovieId);
if (movie == null)
{
return NotFound();
}
var results = Mapper.Map<Movies>(movies);
if (ModelState.IsValid)
{
_moviesRepository.AddMovie(results);
}
return Ok(results);
}
}
Postman
This issue has been fixed. I had to remove the anti-forgery token
I want to pass id to my actionresult method Delete
public ActionResult Delete(Guid AssetTypeId)
{
// _repo.DeleteAssetType(AssetTypeId);
if (_repo.DeleteAssetType(AssetTypeId) == 1)
{
return Index();
}
else
{
TempData["AlertMessage"] = "The DELETE statement conflicted with the REFERENCE constraint ";
return Index();
}
from kendo grid
.Action("Delete", "AssetType",new { AssetTypeId = "#=AssetTypeId#" }))
I guess you have AssetTypeId declared in your schema. In that case you don't need to send it separately. You just need to catch your Model in Delete. For deleting it should look like following; you can see details in their official demo site in here.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingPopup_Destroy([DataSourceRequest] DataSourceRequest request, ProductViewModel product)
{
if (product != null)
{
productService.Destroy(product);
}
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
When I tried redirect to action, the parameter is always null when I received ? I don't know why this happening like these.
ActionResult action1() {
if(ModelState.IsValid) {
// Here user object with updated data
redirectToAction("action2", new{ user = user });
}
return view(Model);
}
ActionResult action2(User user) {
// user object here always null when control comes to action 2
return view(user);
}
And with this I've another doubt. when I accessed action with route, i can get values only by RouteData.Values["Id"]. the values routed doesn't send to parameter.
<a href="#Url.RouteUrl("RouteToAction", new { Id = "454" }> </a>
Here Am I miss any configure ? or anything I miss.
ActionResult tempAction(Id) {
// Here Id always null or empty..
// I can get data only by RouteData.Values["Id"]
}
You cannot pass complex objects in an url like that. You will have to send its constituent parts:
public ActionResult Action1()
{
if (ModelState.IsValid)
{
// Here user object with updated data
return RedirectToAction("action2", new {
id = user.Id,
firstName = user.FirstName,
lastName = user.LastName,
...
});
}
return view(Model);
}
Also notice that I have added the return RedirectToAction instead of only calling RedirectToAction as shown in your code.
But a much better approach is to send only the id of the user:
public ActionResult Action1()
{
if (ModelState.IsValid)
{
// Here user object with updated data
return RedirectToAction("action2", new {
id = user.Id,
});
}
return view(Model);
}
and in your target action use this id to retrieve the user from wherever this user is stored (could be database or something):
public ActionResult Action2(int id)
{
User user = GetUserFromSomeWhere(id);
return view(user);
}
Some alternative approaches (but one I don't recommend or use) is to persist the object in TempData:
public ActionResult Action1()
{
if(ModelState.IsValid)
{
TempData["user"] = user;
// Here user object with updated data
return RedirectToAction("action2");
}
return view(Model);
}
and in your target action:
public ActionResult Action2()
{
User user = (User)TempData["user"];
return View(user);
}
I have an ASP.NET MVC 4 app. I'm relatively new to ASP.NET MVC 4. Currently, I'm trying to build a basic Task list app.
public ActionResult Create()
{
var model = new TaskModel();
return View("~/Views/Task.cshtml", model);
}
[HttpPost]
public ActionResult Create(TaskModel model)
{
if (model.TaskName.Length == 0)
{
// Display error message
}
else
{
// Save to database
// Write success message
}
return View("~/Views/Task.cshtml", model);
}
If there is an error, I display an error message on the screen. My problem is, the previously entered values in the view are not shown. The entire view is blank.How do I preserve the values in the view in this case?
Thank you!
I use TempData for this.
public ActionResult Create()
{
var model = new TaskModel();
TempData["task"] = model;
return View("~/Views/Task.cshtml", model);
}
[HttpPost]
public ActionResult Create()
{
var task = (TaskModel)TempData["task"];
UpdateModel(task);
if (model.TaskName.Length == 0)
{
// Display error message
}
else
{
// Save to database
// Write success message
}
TempData["task"] = task;
return View("~/Views/Task.cshtml", model);
}
MVC works different than WebForms, since there is no concept of 'controls', you have to preserve the state yourself. Another option if you don't want to use TempData is to use an LosFormatter to Serialize your controls into a hidden HTML field. This would replicate the functionality of ViewState in ASP.NET WebForms
My delete method is working but you have to manually refresh the browser to see that it has been deleted. I simply want to reload the page but I can't get it to work. Can someone tell me the proper way to do this?
public virtual ActionResult Index()
{
var recipientOrchestrator = new RecipientsOrchestrator();
RecipientsViewModel model = recipientOrchestrator.GetRecipientsPageData();
return View(model);
}
[HttpPost]
public virtual ActionResult Delete(int id, int applicationId)
{
var recipientOrchestrator = new RecipientsOrchestrator();
recipientOrchestrator.DeleteRecipient(id, applicationId);
return Index();
}
Try
return RedirectToAction("Index");