MVC reload page after Delete - asp.net-mvc-4

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");

Related

MVC - refresh controller SQL data model from View?

I am new to MVC, have some experience in webforms.
I currently have an ActionResult function in my controller that binds all my SQL data to a model, which then I can then successfully build a dataview from in the view.
My issue is that to have everything work properly, I need to call my ActionResult directly in the controller before rendering the page, and this works just fine:
public ActionResult Index()
{
Bind_grid();
return View();
}
public class My_Table
{
public string info_a { get; set; }
public string info_b { get; set; }
public string mod_id { get; set; }
}
public ActionResult Bind_grid()
{
SqlConnection checkitem = new SqlConnection("Data Source=[IPADDRESS];Persist Security Info=True;User ID=userid;Password=password");
string query = "SELECT id, info_a, info_b FROM [my_db].[dbo].[ref_index]";
SqlCommand execute = new SqlCommand(query, checkitem);
var model = new List<My_Table>();
using (checkitem)
{
checkitem.Open();
SqlDataReader rdr = execute.ExecuteReader();
while (rdr.Read())
{
var table = new My_Table();
table.info_a = rdr["info_a"].ToString();
table.info_b = rdr["info_b"].ToString();
table.mod_id = rdr["id"].ToString();
model.Add(table);
}
checkitem.Close();
}
return View(model);
}
I am wondering how to refresh the model from the view instead of requiring it to be ran before returning the view, I've tried AJAX calls and #HTML.Action calls to Bind_grid, but I can't seem to get the page to refresh the data.
Any suggestions in running Bind_grid from a view to refresh the model?
Currently I try this:
function bind_data() {
$.ajax({
url: '#Url.Action("Bind_grid")',
method: 'POST',
});
#{
int p = 0;
foreach (var d in Model)
{
#:console.log(#d.mod_id);
p++;
}
}
}
And I set a javascript interval for 10 seconds to run the bind_data() function,
remove some IDs from the SQL database between intervals,
but the data written to the console is still the original fetched, not the refreshed data.
If I manually refresh the page (F5), I get a correct update of data.
I'm guessing I need to do some kind of partial postback to refresh the razor data, but am not sure the best way to do it in MVC. Any help is appreciated.
You should be able to use the jquery load method, call in your JavaScript interval
$("#grid").load("bind_grid");
Fixed the issue by doing all processing in the codebehind, changed the Bind_grid()
to JsonResult, returning Json(model.ToArray(), JsonRequestBehavior.AllowGet);
Was able to do successful pulls via ajax request.

Post web method not firing + asp.net core webapi

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

how to call actionresult method in my controller from kendo grid in mvc4

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));
}

How to pass a parameter through CRUD in asp.net mvc4?

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 });
}

How do I add new information to the database?

I am working with the following code. I have set up the form, models, and controllers necessary to add an item. I know the code works because after entering text into the text field I am redirect to the correct page. My question is: How do I add the text entered by the user into the default database?
public ActionResult TruckAdd()
{
ViewBag.DisplayText = "Add A Truck";
return View();
}
[HttpPost]
public ActionResult TruckAdd(RegisterTruckModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the Truck
try
{
return RedirectToAction("Index", "Dashboard");
}
catch
{
}
}
// If we got this far, something failed, redisplay form
return View(model);
}