Object Moved Here - RedirectToAction - javascript

Again, after tiresome attempts to solve this annoying issue, I am back here. I am experiencing an "Object moved here" on my view in my MVC5 application after some return RedirectToAction("Index", "Roles", model); action on my controller.
I have considered solutions from the following links:
RedirectToAction and "Object moved to here" error
ASP.NET MVC Website: Object Moved to Here
https://forums.asp.net/t/1643235.aspx?+Object+moved+to+here+problem
but none are applicable to my problem.
Before anyone marks this as a duplicate, please consider the scenario below:
But now the weird thing is that after I have clicked on the 'here' link and it now renders my view - it has a horizontal split screen showing the correct display of my view on top and below the view that throws an Http Error Code - in this case its Error Code 500 : Internal Server Error.
The reason why I am getting the http status code error is due to this unanswered question here (one of many) :
Failed to load resource: Uncaught TypeError: $(...).select2 is not a function
But that is besides the point right now.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Name,Description")] ApplicationRole model)
{
try
{
if (ModelState.IsValid)
{
var role = new ApplicationRole()
{
Name = model.Name,
Description = model.Description
};
var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
var result = await roleManager.CreateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index", "Roles", model);
}
else
{
AddErrors(result);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
// If we got this far, something failed, redisplay form
return View(model);
}
//Below is my index method in my Roles controller which is the action that redirection needs to route to:
[Route("/Roles")]
public ActionResult Index()
{
if (TempData["StatusMessage"] != null)
{
ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
}
else
{
ViewBag.StatusMessage = "";
}
var roles = db.Roles.ToList();
return View("Index", roles);
}
//GET method to create view
public ActionResult Create()
{
return View();
}
View:
#model IEnumerable<User_Manager_Interface.Models.ApplicationRole>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#if (ViewBag.StatusMessage != null)
{
if (ViewBag.StatusMessage != "")
{
string tmp = ViewBag.StatusMessage;
if (tmp.Contains("error"))
{
<div class="notification msgerror">
<a class="close"></a>
<p>#ViewBag.StatusMessage</p>
</div>
}
else
{
<div class="notification msgsuccess">
<a class="close"></a>
<p>#ViewBag.StatusMessage</p>
</div>
}
}
}
<br />
#Html.ActionLink("Create New", "Create", "Roles", new object { }, new { #class = "stdbtn" })
<br />
<br />
<div class="contenttitle radiusbottom0">
<h2 class="table"><span>Roles</span></h2>
</div>
<table cellpadding="0" cellspacing="0" border="0" class="stdtable" id="dyntable">
<colgroup>
<col class="con0" />
<col class="con1" />
<col class="con0" />
</colgroup>
<thead>
<tr>
<th class="head1">Name</th>
<th class="head0">Description</th>
<th class="head1">Options</th>
</tr>
</thead>
<tfoot>
<tr>
<th class="head1">Name</th>
<th class="head0">Description</th>
<th class="head1">Options</th>
</tr>
</tfoot>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</tbody>
</table>
#section Scripts {
#Scripts.Render("~/bundles/tables")
}
Model:
public class ApplicationRole : IdentityRole
{
[Display(Name = "Description")]
[StringLength(100, MinimumLength = 5)]
public string Description { get; set; }
}
"Error" Controller:
public class ErrorController : Controller
{
//
// GET: /Error/
public ActionResult Index(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
return View();
}
}
"Error" View:
#{
ViewBag.Title = Response.StatusCode;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 style="visibility:hidden">#ViewBag.Title</h2>
<div class="errorWrapper">
<h2>An internal server error #ViewBag.Title has occurred</h2>
<h1 class="pageErrorTitle" style="color:red">Error #ViewBag.Title - Page Not Found</h1>
<h3 style="color:black">You may have clicked an expired link or mistyped the address.</h3>
<br />
<a class="default" href="javascript:history.back()">Back to Previous Page</a> <a class="default" href="http://localhost:53648">Return to Dashboard</a>
</div>
Please see screenshots for more visual clarity:
Update:
According to #Munzer 's answer below, I tried to change my Index action method to take in the model route value seeing as though I am passing it in my return statement. See below:
public async Task<ActionResult> Create(ApplicationRole model)
{
if (ModelState.IsValid)
{
var role = new ApplicationRole()
{
Name = model.Name,
Description = model.Description
};
var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
var result = await roleManager.CreateAsync(role);
if (result.Succeeded)
{
//return RedirectToAction("Index", "Roles", model);
return RedirectToAction("SuccessfullyAddedNewRole", "Roles", model);
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult SuccessfullyAddedNewRole(ApplicationRole model)
{
return View(model);
}
But the error still persists. I have tried everything I can think of.

I think the error is here
return RedirectToAction("Index", "Roles", model);
you are passing route values but your index action doesn't accept any, it generate the value itself, you can simple do this instead
return RedirectToAction("Index", "Roles");,
and your index will query the new model, if you want to pass the model, you need to edit your index action accordingly, to accept role model.

Solution can be found on this SO post of mine. Fixed everything :-)
GET http://localhost/Roles/Create 500 (Internal Server Error)

Related

Search bar for an existing list

I have a page (asp.net 6 mvc web app with identity) with a list of users and I want to have a search bar to filter those users by their emails but I have no idea how to do it
Admin controller
public class AdminController : Controller
{
private readonly ILogger<AdminController> _logger;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public AdminController(ILogger<AdminController> logger, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
_logger = logger;
_roleManager = roleManager;
_userManager = userManager;
}
public async Task<IActionResult> ListOfUsersAndRoles()
{
var users = await _userManager.Users.ToListAsync();
var userRolesViewModel = new List<UserRolesViewModel>();
foreach (ApplicationUser user in users)
{
var thisViewModel = new UserRolesViewModel();
thisViewModel.UserId = user.Id;
thisViewModel.Email = user.Email;
thisViewModel.Name = user.UserName;
thisViewModel.Roles = await GetUserRoles(user);
userRolesViewModel.Add(thisViewModel);
}
return View(userRolesViewModel);
}
ListOfUsersAndRoles view
<h1>List of users and roles</h1>
<table class="table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model)
{
<tr>
<td>#user.Email</td>
<td>#string.Join(" , ", user.Roles.ToList())</td>
<td>
<a class="btn btn-primary" asp-controller="Admin" asp-action="ModifyRole" asp-route-userId="#user.UserId">Modify role</a>
</td>
</tr>
}
</tbody>
</table>
This must be so easy to code but as a beginner I'm lost, the tutorials that I'm watching are either for older versions of asp.net or they don't use mvc, EF, identity and so on so instead of learning, I'm actually getting more and more confused. From what I'm seeing, I think javascript is necessary and I have no knowledge in javascript
Any videos, websites or advices are welcome
Since you have no knowledge in javascript, So I try to write a simple demo to achieve your goal without javascript, Please refer to this:
ViewModel
public class SearchViewModel
{
public string Email { get; set; }
public IEnumerable<string> Role { get; set; }
public string UserId { get; set; }
}
Controller
public class SearchController : Controller
{
private readonly RoleManager<IdentityRole> roleManager;
//if you don't use custom identityuser, you just use UserManager<IdentityUser> here
private readonly UserManager<AppUser> userManager;
public SearchController(UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
{
this.userManager = userManager;
this.roleManager = roleManager;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Index(SearchViewModel model)
{
var user = await userManager.FindByEmailAsync(model.Email);
if(user != null)
{
var role = await userManager.GetRolesAsync(user);
SearchViewModel viewModel = new SearchViewModel()
{
Role = role,
Email = user.Email,
UserId = user.Id
};
return View(viewModel);
}
else
{
ViewBag.result = "User not found";
return View();
}
}
}
Index
#model SearchViewModel
<h1>List of users and roles</h1>
<form asp-controller="Search" asp-action="Index" method="post">
<input asp-for="#Model.Email" />
<button type="submit">search</button>
</form>
<table class="table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if (#Model!=null)
{
<tr>
<td>#Model.Email</td>
<td>
#foreach (var role in #Model.Role)
{
<div>#role</div>
}
</td>
<td>
<a class="btn btn-primary" asp-controller="Admin" asp-action="ModifyRole" asp-route-userId="#Model.UserId">Modify role</a>
</td>
</tr>
}
else
{
<h3> #ViewBag.result</h3>
}
</tbody>
</table>
Demo:

When rendering my partial view it is not set it an instance of an object

I am attempting to use partial views for the first time and I need some help. I am posting a string from Javascript to my ASP controller so that I can query my database using that string. Like so:
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
error: function (e) {
console.log(e)
console.log("error")
}
});
}
Controller
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
string county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from SOP in _context.SalesOffice_Plant
where SOP.County == county
select new SalesOffice_Plant
{
Employee = SOP.Employee
};
return PartialView(query.ToList());
}
[HttpGet]
public ActionResult Index()
{
ViewData["Title"] = "Contact Us";
ViewBag.Current = "Contact";
return View();
}
When I set break points - I can see that the string is passed correctly and my LINQ query works just fine. My problem occurs when I want to render a table of the employees in my Index page. The JavaScript returns a value to the controller after the page loads. This means I needed a way to "refresh the page". I was told to use a partial view to solve this problem and this is what I came up with.
Index.cshtml
#model IEnumerable<Project.Models.SalesOffice_Plant>
//A bunch of Html
#await Html.PartialAsync("_IndexPartial")
//More Html
_IndexPartial.cshtml
#model IEnumerable<Project.Models.SalesOffice_Plant>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employee)
</td>
</tr>
}
</tbody>
Ideally, I would like a table of Employees to be generated and displayed in the Index.cshtml. However, when I load the page I get and error telling me that my #await Html.PartialAsync("_IndexPartial") 'is not set to an instance of an object.
Any pointers in the right direction would be very helpful.
When you use ajax,it would not reload your page after backend code finishing,so you need to use .html() method to render the backend result to html.
Here is a whole working demo:
Model:
public class SalesOffice_Plant
{
public int Id { get; set; }
public string County { get; set; }
public string Employee { get; set; }
}
View(Index.cshtml):
<button type="button" onclick="findEmployees('a ')">Find</button>
<div id="employee">
</div>
#section Scripts
{
<script>
function findEmployees(userCounty) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
error: function (e) {
console.log(e)
console.log("error")
},
success: function (res) {
$("#employee").html(res); //add this...
}
});
}
</script>
}
Partial View(_IndexPartial.cshtml):
#model IEnumerable<SalesOffice_Plant>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employee)
</td>
</tr>
}
</tbody>
</table>
Controller:
[HttpPost]
public ActionResult Index([FromBody] string userCounty)
{
string county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from SOP in _context.SalesOffice_Plant
where SOP.County == county
select new SalesOffice_Plant
{
Employee = SOP.Employee
};
return PartialView("_IndexPartial", query.ToList()); //must specify the partial view name
//otherwise it will match the action name as partial view name
}
[HttpGet]
public ActionResult Index()
{
ViewData["Title"] = "Contact Us";
ViewBag.Current = "Contact";
return View();
}
Result:

Sort list of objects in MVC

I am trying to build page that shows all selected movies depending on genre,
with $.post
If genre is not selected page should show all movies.It is default selection.
This is Controller code:
public class BrowseController : Controller
{
private MovieContext context = new MovieContext();
// GET: Browse
public ActionResult Index()
{
ViewBag.Genres = context.Genre.ToList();
IEnumerable<Movie> mov = TempData["movies"] as IEnumerable<Movie>;
if (mov == null)
{
IEnumerable<Movie> movies = context.Movies.ToList();
return View(movies);
}
return View(mov);
}
[HttpPost]
public ActionResult Index(int id = -1)
{
IEnumerable<Movie> model;
if (id != -1)
{
model = context.Movies.Where(x => x.GenreId == id);
}
else
{
model = context.Movies.ToList();
}
ViewBag.Genres = context.Genre.ToList();
TempData["movies"] = model;
return RedirectToAction("", "Browse");
}
}
And this is the view code:
#model IEnumerable<Movies.Models.Movie>
#using Movies.Models
#{
ViewBag.Title = "Index";
var Movie = Model.FirstOrDefault();
List<Genre> Genres = ViewBag.Genres;
}
#Html.DropDownListFor(m => Movie.GenreId, new SelectList(Genres, "Id",
"Name"), "")
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Rating)
</th>
<th>
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rating)
</td>
<td></td>
</tr>
}
</table>
#section Scripts{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$('select#Movie_GenreId').on('change', function () {
var value = $(this).find(':selected').val();
var url = "/Browse/Index";
$.post(url, { id: value });
});
</script>
}
I checked Chrome Debugging tool and Network tab and I see in Preview tab of response that there are no errors and Get Browse/Index action is returning expected results but I don't see them in View. Not sure why.
You make a POST request , but you don't handle the response. For instance, you forget to update the DOM structure.
For doing this, you have to attach a callback function to the returned response.
$.post(url, { id: value },function(response){
//here is request response
});
Also, when you use AJAX, the purpose is to update DOM without refresh page to see the updates.
The solution is to return a JSON object with all the informations and then, handle them in the callback function of $.post method.

MVC How to hit the controller method when Partial view (create) submitted

Create click (2nd Partial view) is not hit into action controller. I have used two partial view. I tried the below steps. please see the attached screen shot
While clicking Add button (Index), Dropdown Selected value is added into partial view(1st partial view)
On Click Edit, another partial view(2nd) is loaded into div.
2'nd PV (Create) click, i'm planning to validate model(SubmitReview), generate xml and update to previous partial view, but this is not happening. please see the below code and suggest me how to achieve?
public ActionResult Index()
{
var DBQList = DBActivity.Getdbqlist();
DBQModel viewmodel = new DBQModel();
var DBQSelectList = new SelectList(DBQList, "DBQ_ID", "DBQ_Name", "IsSelected");
viewmodel.selectList = DBQSelectList;
Session["Session_DBQModel"] = viewmodel;
return View(viewmodel);
}
[HttpPost]
public ActionResult Index(DBQModel dbqModel)
{
if (ModelState.IsValid)
{
//
}
var mdl = (DBQModel)Session["Session_DBQModel"];
var selectedvalue = Convert.ToInt32(Request.Form["SelectedId"].ToString());
var rows = DBActivity.Getdbqlist().FirstOrDefault(x => x.DBQ_ID == selectedvalue);
if (rows != null)
{
DBQTable tbl = new DBQTable();
tbl.DBQ_ID = rows.DBQ_ID;
tbl.DBQ_Name = rows.DBQ_Name;
tbl.DBQ_Desc = rows.DBQ_Desc;
tbl.VAFormNo = rows.VAFormNo;
mdl.dbqTable.Add(tbl);
}
Session["Session_DBQModel"] = mdl;
return View(mdl);
}
public PartialViewResult LoadDBQ(int id)
{
if (id==1)
{
EatingDisorder eatingDisorder = new EatingDisorder();
return PartialView("_EatingDisorderPV", eatingDisorder);
}
return PartialView("_DefaultPV");
}
[HttpPost]
public ActionResult SubmitReview(EatingDisorder _model)
{
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
if (_model.s1_Bulima)
{
if ((_model.s1_Bulima_Date != null) && (string.IsNullOrEmpty(_model.s1_Bulima_ICD)) && (!string.IsNullOrEmpty(_model.s1_Bulima_Name)))
{
//ok
}
else
{
ModelState.AddModelError("s1_Bulima_Date", "s1_Bulima_Date is required.");
ModelState.AddModelError("s1_Bulima_ICD", "s1_Bulima_ICD is required.");
ModelState.AddModelError("s1_Bulima_Name", "s1_Bulima_Name is required.");
}
}
//save to db
//return Json(new { Result = "OK" });
}
catch (Exception ex)
{
//return Json(new { Result = "ERROR", Message = ex.Message });
ModelState.AddModelError("", ex.Message);
}
return PartialView("_EatingDisorderPV", _model);
}
Iindex.cshtml
#model WebApplication1.Models.DBQModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.DropDownListFor(n => n.SelectedId, Model.selectList, "Please select dbq", new { #class = "from-control col-md-4" })
<input type="submit" value="Add" class="btn btn-default" />
#Html.Partial("_DBQGridPV", Model.dbqTable)
<div id="DBQHolder"></div>
}
_DBQGridPV.cshtml
#model IEnumerable<WebApplication1.Models.DBQTable>
<table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.DBQ_ID)</th>
.....
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.DBQ_ID)</td>
.....
<td>
#Ajax.ActionLink("Edit", "LoadDBQ", new { id = item.DBQ_ID },
new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "DBQHolder", InsertionMode = InsertionMode.Replace })|
#Html.ActionLink("Delete", "DeleteDBQ", new { id = item.DBQ_ID })
</td>
</tr>
}
</table>
_EatingDisorderPV.cshtml
#model WebApplication1.Models.EatingDisorder
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
.....
<input type="submit" value="Create" />
}

Getting a NULL value back for a Model when I see it is NOT NULL during debugging

I have a "Details" View that I am displaying to the user to find out if any statuses are associated with any projects.
When the "GET" for the "Details" view is performed, only a dropdownlist appears asking the user to select an item from the list. In the View, I simply check if the "Model" is null to display the rest of the view or not (the associated projects for that status).
During the "POST", a "status" is retrieved with its associated 'projects'. While coming back into the View, I am expecting the Model not to be null (since it found a status and its associated projects).
If the Model is not null, I want to display the rest of the View.
In the "POST", why is the Model still null? See below code & screenshots. Please copy and paste the screenshot to your favorite image viewer for better viewing.
fyi, after looking in the browser with the debugging tool, I can see that there is no html displayed after the dropdownlist?????
Model
namespace YeagerTechDB.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
[Serializable, DataContract(IsReference = true)]
public partial class Status
{
public Status()
{
Projects = new HashSet<Project>();
}
[Key]
[ScaffoldColumn(true)]
[DataMember]
public short StatusID { get; set; }
[Required]
[StringLength(30)]
[Display(Name = "Status")]
[DataMember]
public string StatusDescription { get; set; }
[DataMember]
public virtual ICollection<Project> Projects { get; set; }
}
}
JS
$.ajax({
url: Url,
data: JSON.stringify(status_Input),
//data: AddAntiCSRFToken(JSON.stringify(status_Input)),
dataType: "html",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
beforeSend: function ()
{
$('<div id="divLoadMsg" style="text-align:center"><img src="~/Content/progress.gif" /><br/><b>Please wait...</b></div>').dialog({
modal: true, resizable: false, height: 'auto', width: 'auto', minHeight: '30px',
open: function () { $('.ui-dialog-titlebar').hide(); }, close: function () { $('.ui-dialog-titlebar').show(); $(this).dialog('destroy').remove() }
});
},
success: function (data, status)
{
if (status == "success")
{
// Retrieved data
}
},
CONTROLLER
// GET: Statuses/StatusProjects/Details
public ActionResult Details()
{
return View();
}
// POST: Statuses/StatusProjects/Details/5
[HttpPost]
public async Task<ActionResult> Details(short? id)
{
if (id == null)
{
return View("IDIsNull");
}
Status status = await db.GetProjectsByStatusIDAsync(id);
if (status == null)
{
return View("ObjectModelNull");
}
return View();
}
VIEW
#model YeagerTechDB.Models.Status
#using YeagerTechDB.ViewModels.Statuses
#{
ViewBag.Title = "Statuses";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Select Status to see associated Projects</h3>
<div>
#Html.Partial("_SelectStatusProjects", new StatusesDDL());
</div>
#if (Model != null) // Needed for GET
{
<div>
<table class="table table-condensed">
<tr>
<th>
Associated Projects for selected Status
</th>
<th></th>
</tr>
<tr>
<th align="right">Project ID</th>
<th>Project Description</th>
<th>Project Name</th>
<th align="right">Quote</th>
<th>Notes</th>
<th>Created Date</th>
<th>Updated Date</th>
</tr>
<tbody>
#foreach (var item in Model.Projects)
{
<tr>
<td align="right">
#Html.DisplayFor(m => item.ProjectID)
</td>
<td>
#Html.DisplayFor(m => item.Description)
</td>
<td>
#Html.DisplayFor(m => item.Name)
</td>
<td align="right">
#Html.DisplayFor(m => item.Quote)
</td>
<td>
#Html.DisplayFor(m => item.Notes)
</td>
<td>
#Html.DisplayFor(m => item.CreatedDate)
</td>
<td>
#Html.DisplayFor(m => item.UpdatedDate)
</td>
</tr>
}
</tbody>
</table>
</div>
}
EDIT
After making the change that Kundan suggested, I can tell during debugging, if I step through the code, it goes into the View after the POST. The Model is not null and it then properly cycles through the child records that I want displayed on the screen.
However, after that is finished, those records are not displayed on the browser window! The only thing that appears is the dropdownlist again without any display beneath that.
Nothing else is executed after the debugging of the View on the POST which is correct.
The only change that was made in this process is returning the object model of the View (status) as Kundan suggested.
How come the records are not being displayed in the browser after the POST?
fyi, after looking in the browser with the debugging tool, I can see that there is no html displayed after the dropdownlist?????
fyi, I also tried running the page without the dropdownlist and forcing in a value during debugging which would bring back some projects, the same way as if I had selected it from the drop down list. Even with the html removed for the dropdownlist, it went through the View cycled through the collection, but did not emit any html?
Here are the screen shots...
The Model is null because you didn't pass back it to View from your controller. The code should be like below:
[HttpPost]
public async Task<ActionResult> Details(short? id)
{
if (id == null)
{
return View("IDIsNull");
}
Status status = await db.GetProjectsByStatusIDAsync(id);
if (status == null)
{
return View("ObjectModelNull");
}
return View(status);
}
This will fix your issue.

Categories

Resources