Parameters from view not getting to controller action method - asp.net-mvc-3

I'm implementing Troy Goode's PagedList in one of my views (ASP.NET MVC 3 Razor). The challenge I'm having is when I click on a page number link, the request is routed to my HttpGet method, which just returns the empty page (ready for input).
My View Model:
public class SearchViewModel
{
public SelectList IndustrySelectList { get; set; }
public IPagedList<KeyValuePair<string, SearchResult>> SearchResults { get; set; }
public PagingInfo PagingInfo { get; set; }
}
Controller:
[HttpGet]
public ViewResult Search(string searchTerm = "")
{
SearchViewModel vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName"),
PagingInfo = new PagingInfo
{
CurrentPage = 1,
ItemsPerPage = 25,
TotalItems = 0
}
};
return View(vm);
}
[HttpPost]
public ActionResult Search(string[] industries, string searchTerm = "", int page = 1)
{
SearchViewModel vm = null;
_url = "http://localhost/MasterNode/masternode.cgi?zoom_query={" + searchTerm + "}&zoom_xml=1&zoom_page={startPage?}&zoom_per_page=1000";
StringBuilder sb = new StringBuilder();
int pageSize = 5;
if (string.IsNullOrEmpty(searchTerm))
{
vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName")
};
}
else
{
_request = new SearchRequest(SearchRequest.EnvironmentTypes.Development, "", _url, searchTerm, SearchRequest.SearchType.AllWords, 1000);
sb.Append(GetResults(_url));
_results = new Dictionary<string, SearchResult>();
ParseResults(sb);
GetDetailInformationForResults(searchTerm);
vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName"),
SearchResults = _results.ToList<KeyValuePair<string, SearchResult>>().ToPagedList(1, 25),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = pageSize,
TotalItems = _results.Count()
}
};
}
return View(vm);
}
View:
#model MultiView.OmniGuide.ViewModels.SearchViewModel
#using MultiView.OmniGuide.HtmlHelpers
#using PagedList
#using PagedList.Mvc
#{
ViewBag.Title = "Search";
}
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("Search", "Home"))
{
#Html.HiddenFor(c => c.IndustrySelectList)
#Html.HiddenFor(c => c.PagingInfo)
#Html.HiddenFor(c => c.SearchResults)
<table width="70%">
<tr>
<td colspan="2" style="background: #fff">
<input id="searchTerm" name="searchTerm" type="text" class="SearchBox" style="width: 450px" />
<input type="submit" class="SearchButton" value=" " />
</td>
</tr>
<tr align="left">
<td align="left" style="background: #fff">
#Html.ActionLink("MultiView corporate site", "Search")
</td>
</tr>
<tr>
<td colspan="1" align="center" style="width: 450px">
#{
Html.Telerik().PanelBar()
.Name("searchPanel")
.Items(title =>
{
title.Add()
.Text("Filter by Industry")
.Content(() =>
{
#Html.RenderPartial("_Industry", #Model);
});
})
.Render();
}
</td>
</tr>
<tr><td colspan="2"></td></tr>
</table>
<br />
if (Model.SearchResults != null)
{
<table width="70%">
<tr>
<th>
Company Image
</th>
<th class="tableHeader">
Company Name Here
</th>
<th class="tableHeader">
Website
</th>
</tr>
#foreach (KeyValuePair<string, MultiView.OmniGuide.Models.SearchResult> itm in Model.SearchResults)
{
<tr>
<td align="left" style="width: 15%">
#itm.Value.DetailedInfo.LogoURL
</td>
<td align="left" style="width: 60%">
<p style="text-align: left">
#itm.Value.DetailedInfo.DescriptionAbbreviated
<br />
</p>
#Html.AnchorLink(itm.Value.FoundURL, itm.Value.FoundURL)
</td>
<td style="width: 25%">
#itm.Value.FoundURL
</td>
</tr>
}
</table>
#Html.PagedListPager((IPagedList)Model.SearchResults, page => Url.Action("Search", "Home", new { page }))
}
}
When text is supplied in the input box and the button is clicked, the requested is routed to the HttpPost method. In looking at the request.form values, all expected data but paging information is present.
?HttpContext.Request.Form.AllKeys
{string[5]}
[0]: "IndustrySelectList"
[1]: "PagingInfo"
[2]: "SearchResults"
[3]: "searchTerm"
[4]: "industries"
Any help with this would be very much appreciated!

By clicking the button you are submitting the form which is why it is doing the httppost. The next page link is hitting the httpget correctly but you are not passing it any information to so that it knows what to get. The get needs other information, like what page you are wanting.

The page number links fire a GET request, so you'll need to make sure that your GET action can handle the full search as well, so will need to get the page number and industries array - using defaults for when those parameters aren't available.
e.g.
[HttpGet]
public ViewResult Search(string searchTerm = "", int page = 1,
string industries = "")
{
//.....
}
You'll need to modify the pager link like this to pass industries to the get action.
#Html.PagedListPager((IPagedList)Model.SearchResults, page => Url.Action("Search", "Home", new { page, industries = string.Join(",", Model.IndustrySelectList.Where( x => x.Selected).Select( x => x.Text)) }))
It's not clear to me from your code where the post action is getting string[] industries from, or what it is doing with it, but you will need some way of passing this same this to your get action, probably as a single string that is comma separated. The example I've provided assumed you are taken it from the select list on the viewmodel

Related

.NET Core 6 Pull Down Menu Selection to Group through View Model

I am having partial success searching / grouping data through a viewmodel:
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Model
using System.ComponentModel.DataAnnotations; // Date Format
namespace Project01Name.Models
{
public class Class01Name
{
public int Id { get; set; }
public string? String01Name { get; set; }
public string? String02Name { get; set; }
public int? Int01Name { get; set; }
public bool? Bool01Name { get; set; }
[DataType(DataType.Date)]
public DateTime? DateTime01Name { get; set; }
}
}
**
View Model
**
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace Project01Name.Models.ViewModelsName
{
public class SearchByGroupName
{
public List<Class01Name>? Class01NameList { get; set; } // A list of movies.
public SelectList? String02NameSelection { get; set; } // A SelectList containing the list of genres. This allows the user to select a genre from the list.
public string? String02NameSelected { get; set; } // MovieGenre, which contains the selected genre.
public string? SearchString { get; set; } // SearchString, which contains the text users enter in the search text box.
}
}
Controller Action Method
// GET: String01Names
public async Task<IActionResult> Index2(string class01NameGroup, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> string02NameQuery = from m in _context.Class01Name
orderby m.String02Name
select m.String02Name;
var selectVariable = from m in _context.Class01Name
select m;
if (!string.IsNullOrEmpty(searchString))
{
selectVariable = selectVariable.Where(s => s.String01Name!.Contains(searchString));
}
if (!string.IsNullOrEmpty(class01NameGroup))
{
selectVariable = selectVariable.Where(x => x.String02Name == class01NameGroup);
}
var string02NameVM = new SearchByGroupName
{
String02NameSelection = new SelectList(await string02NameQuery.Distinct().ToListAsync()),
Class01NameList = await selectVariable.ToListAsync()
};
return View(string02NameVM);
}
View
#model Project01Name.Models.ViewModelsName.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" asp-items="Model.String02NameSelection"> <option value="">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" value="Filter" />
#*<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a> *#
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Not filtering data...simply changes pull down menu back to "All,"
displaying all data. Data not filtered.
**Question: ** What in the code has to be changed to have the data filtered successfully?
Well, seems you wanted to implement searching functionality in way, so that you can filter with the dropdown and search box and finally if you select All as dropdown value you want to load all the list without any filter and shorting means the full list which comes at first view.
If so, you need to use javascript for your dropdown change event as cshtml doesn't deal with change event. In addition, as you are using asp.net core MVC which would return HTML View altough, we need json data for Ajax reponse but we are would bee getting HTML View. So Ajax success Function will through an error where we would use filter with All parameter.
Modification Required:
Javascript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Note:
As you can see, in success function we are doing nothing, because it will always throuh an error because we are not returning json. Thus, we will work in error section. indow.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";. Here, for your understanding, we will call this function when we select All as our dropdown value in that scenario, we will pass All and nothing , nothing will convert into null and all will be our search key.
Modify Your Existing View:
In your existing view, replace blow dropdown code snippet , means the select items
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Note: If you notice I hav introduced a id id="allId" which will be using on dropdown change event.
Controller:
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Complete Demo:
Full Controller With Seed Model Class Value:
public class SearchController : Controller
{
public static List<Class01Name> listOfClass01Name = new List<Class01Name>()
{
new Class01Name() { Id =101, String01Name ="Titanic",String02Name = "Romantic", Int01Name =01, Bool01Name = false, DateTime01Name = new DateTime(2023-01-15) },
new Class01Name() { Id =102, String01Name ="Forest gump",String02Name = "Motivational", Int01Name =02, Bool01Name = true, DateTime01Name = new DateTime(2023-01-12) },
new Class01Name() { Id =103, String01Name ="Spider Man",String02Name = "Action", Int01Name =03, Bool01Name = false, DateTime01Name = new DateTime(2023-01-10) },
new Class01Name() { Id =104, String01Name ="Harry Potter",String02Name = "Suspense", Int01Name =04, Bool01Name = true, DateTime01Name = new DateTime(2023-01-13)},
};
public List<SelectListItem> String02NameSelectionList = new List<SelectListItem>()
{
new SelectListItem { Text = "Motivational", Value = "Motivational" },
new SelectListItem { Text = "Romantic", Value = "Romantic" },
new SelectListItem { Text = "Action", Value = "Action" },
new SelectListItem { Text = "Comedy", Value = "Comedy" }
};
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Full View:
#model DotNet6MVCWebApp.Controllers.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" name="searchString" />
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Output:

asp.net core mvc, make view that all come from string object's html code as a string

I want to make a model that takes all the html codes from dynamic string object. Like this:
Model for dynamic html:
public class PageHtmlModel
{
public string HtmlCode { get; set; }
}
Entity Model
public class Entity
{
private int _ID;
private string _Module;
private string _Explanation;
private string _Situation;
private string _Personel;
private string _PersonelsNotes;
private string _EndDate;
public int id { get => _ID; set => _ID = value; }
public string module { get => _Module; set => _Module = value; }
public string explanation { get => _Explanation; set => _Explanation = value; }
public string situation { get => _Situation; set => _Situation = value; }
public string personel { get => _Personel; set => _Personel = value; }
public string personels_notes { get => _PersonelsNotes; set => _PersonelsNotes = value; }
public string end_date { get => _EndDate; set => _EndDate = value; }
}
DataAccesLayer:
public static string html()
{
PageHtmlModel pageHtmlModel = new PageHtmlModel();
//Thats All html page comes from string
pageHtmlModel.HtmlCode = "#model deneme100.Models.Entity <html> <head> <link href='~/css/invoice.css' rel='stylesheet' /> </head> <body> <div class='index-box'> <table cellpadding='0' cellspacing='0'> <tr class='top'> <td colspan='2'> <table> <tr> <td class='title'> <img src='~/img/logo.png' style='width:100%; max-width:300px;' /> </td> <td> #Html.DisplayNameFor(model => model.id):#Html.Raw(Model.id) <br>#Html.DisplayNameFor(model => model.module):#Html.Raw(Model.module) <br>#Html.DisplayNameFor(model => model.explanation):#Html.Raw(Model.explanation) </td> </tr> </table> </td> </tr> <tr class='information '> <td colspan='2 '> <table> <tr> <td> #Html.DisplayNameFor(model => model.situation):#Html.Raw(Model.situation) <br>#Html.DisplayNameFor(model => model.end_date):#Html.Raw(Model.end_date) </td> <td> </td> </tr> </table> </td> </tr> <tr class='heading '> <td> #Html.DisplayNameFor(model => model.personels_notes) </td> <td></td> </tr> <tr class='item'> <td> #Html.Raw(Model.personels_notes) </td> </tr> <tr class='total '> <td></td> <td> #Html.DisplayNameFor(model => model.personel):#Html.Raw(Model.personel) </td> </tr> </table> </div> </body> </html>";
return (pageHtmlModel.HtmlCode);
}
This is My Index Page For Open The Other Dynamic Model Pages
//This is catching object id for entity object
$('#myTable tbody').on('click', '#pdf', function () {
if (!($(this).closest('tr').hasClass('selected'))) {
table.$('tr.selected').removeClass('selected');
$(this).closest('tr').addClass('selected');
}
obj = {}
obj.id = $('tr.selected td').eq(0).html();
window.location = "/Home/PDF/" + obj.id;
if ($(this).closest('tr').hasClass('selected')) {
$(this).closest('tr').removeClass('selected');
}
})
Controller
public IActionResult PDF(int id)
{
var result = new EntityDataAccess.DataObject();
result.data = EntityDataAccess.OneObject(new Entity() { id = id });
return View(EntityDataAccess.html(), result.data[0]);
}
View => I just want to write this and see my all html page
#model myProject.Models.PageHtmlModel
#{
ViewData["Title"] = "PDF";
Layout = null;
}
thanks for helping from now
Well, you can use #Html.Raw() HTML helpers to bind your dynamic HTML on your view. Here is the example for you.
Controller Action:
[HttpGet]
public IActionResult BindDynamicToHtml()
{
StringBuilder sb = new StringBuilder();
var convertedHtmlBody = "";
sb.Append("<!DOCTYPE html>");
sb.Append("<html>");
sb.Append("<head>");
sb.Append("</head>");
sb.Append("<body>");
sb.Append("<p>Dear Coder,</p>");
sb.Append("<p>Please check the following answer. This is how you can generate dynamic HTML to View</p>");
sb.Append("<div style='max - height:500px; overflow: auto; width: 100 %; border - spacing: 0; '>");
sb.Append("<style> table, th, td { border: 1px solid black; } th{ padding:2px; } </style>");
sb.Append("<table style='width:20%;'>");
sb.Append("<tr>");
sb.Append("<th style='color:red;text-align:left;'>Test Bindings</th>");
sb.Append("<th style='text-align:right'>40</th>");
sb.Append("</tr>");
sb.Append("</table>");
sb.Append("<br />");
sb.Append("<table style='width:20%;text-align:center;'>");
sb.Append("<tr style='color:red;'>");
sb.Append("<th style='text-align:center'>Name</th>");
sb.Append("<th style='text-align:center'>Violations</th>");
sb.Append("<th style='text-align:center'>Details</th>");
sb.Append("</tr>");
sb.Append("</table>");
sb.Append("</div>");
sb.Append("<hr/>");
sb.Append("<p><strong style='color: red'>Note:</strong> For more details please check details: <a href='https://stackoverflow.com/users/9663070/md-farid-uddin-kiron'>Details</a></p>");
sb.Append("</body>");
sb.Append("</html>");
convertedHtmlBody = sb.ToString();
ViewBag.bindToHtmlInView = convertedHtmlBody;
return View(); ;
}
View:
#{
ViewData["Title"] = "BindDynamicToHtml";
}
#Html.Raw(ViewBag.bindToHtmlInView)
Output:
Note: If you would like to learn more about power of HTML helper you could refer to our official document here and this one
Hope it would help you to resolve your problem.

I lost my data on submit MVC 3

I have a MVC 3 application with entity framework.
In my page I use a custom Model that contains all objects I use. The page is rendered perfectly, but when I press the submit button my object loses the data.
This is my custom model:
public class ControleAcessoModel
{
private List<Controle> controles = new List<Controle>();
public GRUPO_ACESSO_TB grupo_acesso_tb { get; set; }
public List<Controle> Controles
{
get
{
return controles;
}
}
public void AddTela(byte id, string nome)
{
Controle ctrl = new Controle();
ctrl.ID_TELA = id;
ctrl.NM_TELA = nome;
controles.Add(ctrl);
}
public class Controle
{
public bool Selecionado { get; set; }
public byte ID_TELA { get; set; }
public string NM_TELA { get; set; }
public bool FL_SALVAR { get; set; }
public bool FL_ALTERAR { get; set; }
public bool FL_EXCLUIR { get; set; }
}
}
this is my Razor Html code:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<table>
<tr>
<th>Salvar</th>
<th>Editar</th>
<th>Excluir</th>
<th>Tela</th>
</tr>
#foreach (var item in Model.Controles)
{
<tr>
<td style="text-align: center">
#Html.EditorFor(modelItem => item.FL_SALVAR)
</td>
<td style="text-align: center">
#Html.EditorFor(modelItem => item.FL_ALTERAR)
</td>
<td style="text-align: center">
#Html.EditorFor(modelItem => item.FL_EXCLUIR)
</td>
<td>
#Html.DisplayFor(modelItem => item.NM_TELA)
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Salvar" />
</p>
}
This is my create code, where I put the data on database.
Is in this part, that my object controleacessomodel is empty.
[HttpPost]
public ActionResult Create(ControleAcessoModel controleacessomodel, byte id)
{
if (ModelState.IsValid)
{
for (int i = 0; i < controleacessomodel.Controles.Count; i++)
{
if (ValidaSelecao(controleacessomodel.Controles[i]))
{
PERMISSAO_GRUPO_ACESSO_TELA_TB permissao = new PERMISSAO_GRUPO_ACESSO_TELA_TB();
permissao.ID_GRUPO_ACESSO = controleacessomodel.grupo_acesso_tb.ID_GRUPO_ACESSO;
permissao.ID_TELA = controleacessomodel.Controles[i].ID_TELA;
permissao.FL_SALVAR = controleacessomodel.Controles[i].FL_SALVAR;
permissao.FL_ALTERAR = controleacessomodel.Controles[i].FL_ALTERAR;
permissao.FL_EXCLUIR = controleacessomodel.Controles[i].FL_EXCLUIR;
db.PERMISSAO_GRUPO_ACESSO_TELA_TB.AddObject(permissao);
}
}
db.SaveChanges();
return RedirectToAction("Edit", "GrupoAcesso", new { id = id });
}
return View(controleacessomodel);
}
Why my object is empty after submit?
It's not possible to use the Foreach loop construct as the generated ids will be not be correct, therefore MVC is not able to map the values back to the model. You need to use a for loop instead:
#for (int i = 0 ; i < Model.Controles.Count; i++)
{
<tr>
<td style="text-align: center">
#Html.EditorFor(m => m.Controles[i].FL_SALVAR)
</td>
<td style="text-align: center">
#Html.EditorFor(m => m.Controles[i].FL_ALTERAR)
</td>
<td style="text-align: center">
#Html.EditorFor(m => m.Controles[i].FL_EXCLUIR)
</td>
<td>
#Html.DisplayFor(m => m.Controles[i].NM_TELA)
</td>
</tr>
}
Phil Haack write a good blog post about this. Also Scott Hanselman wrote a nice post too.

Is there an #Html.ActionLink equivilent for HttpPost?

I have a table that I need to add links to. The links need to go to an HTTPPost actionResult on my controller. I have a huge list that the user needs to be allowed to click on the status, hit the controller and route to the appropriate page afterward. #Html.ActionLink is an HttpGet action. Is there an equivalent for a post?
<table class="table table-striped table-bordered">
<th>Ssn</th>
<th>State</th>
<th>File Uploaded Date</th>
<th>Claim Status</th>
#foreach (var currentClaim in Model.CurrentClaims)
{
<tr >
<td><span name="Ssn">#currentClaim.SSN</span></td>
<td>#currentClaim.StateName</td>
<td>#currentClaim.ClaimDate</td>
<td>#Html.ActionLink(#currentClaim.ClaimStatus, "SubmitClaim", "Claim", FormMethod.Post, new ClaimInputModel { SSN = currentClaim.SSN, StateId = currentClaim.StateId })</td>
</tr>
}
</table>
I tried using
#using("SubmitClaim", "Claim", FormMethod.Post, new ClaimInputModel { SSN = currentClaim.SSN, StateId = currentClaim.StateId })
{
<button type="submit" >xxx</button>
}
I get an HttpCompiler error with this.
You need to use the BeginForm() HtmlHelper that returns a MvcForm which implements IDisposable...
#using(Html.BeginForm("SubmitClaim", "Claim", FormMethod.Post, new { SSN = currentClaim.SSN, StateId = currentClaim.StateId }))
{
<button type="submit" >xxx</button>
}

How to pass a list of objects instead of one object to a POST action method

I have the following GET and POST action methods:-
public ActionResult Create(int visitid)
{
VisitLabResult vlr = new VisitLabResult();
vlr.DateTaken = DateTime.Now;
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description");
return View();
}
//
// POST: /VisitLabResult/Create
[HttpPost]
public ActionResult Create(VisitLabResult visitlabresult, int visitid)
{
try
{
if (ModelState.IsValid)
{
visitlabresult.VisitID = visitid;
repository.AddVisitLabResult(visitlabresult);
repository.Save();
return RedirectToAction("Edit", "Visit", new { id = visitid });
}
}
catch (DbUpdateException) {
ModelState.AddModelError(string.Empty, "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
}
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description", visitlabresult.LabTestID);
return View(visitlabresult);
}
Currently the view display the associated fields to create only one object,, but how i can define list of objects instead of one object to be able to quickly add for example 10 objects at the same “Create” request.
My Create view look like:-
#model Medical.Models.VisitLabResult
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#section scripts{
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>VisitLabResult</legend>
<div class="editor-label">
#Html.LabelFor(model => model.LabTestID, "LabTest")
</div>
<div class="editor-field">
#Html.DropDownList("LabTestID", String.Empty)
Your viewModel
public class LabResult
{
public int ResultId { get; set; }
public string Name { get; set; }
//rest of the properties
}
Your controller
public class LabController : Controller
{
//
// GET: /Lab/ns
public ActionResult Index()
{
var lst = new List<LabResult>();
lst.Add(new LabResult() { Name = "Pravin", ResultId = 1 });
lst.Add(new LabResult() { Name = "Pradeep", ResultId = 2 });
return View(lst);
}
[HttpPost]
public ActionResult EditAll(ICollection<LabResult> results)
{
//savr results here
return RedirectToAction("Index");
}
}
Your view
#model IList<MvcApplication2.Models.LabResult>
#using (Html.BeginForm("EditAll", "Lab", FormMethod.Post))
{
<table>
<tr>
<th>
ResultId
</th>
<th>
Name
</th>
</tr>
#for (int item = 0; item < Model.Count(); item++)
{
<tr>
<td>
#Html.TextBoxFor(modelItem => Model[item].ResultId)
</td>
<td>
#Html.TextBoxFor(modelItem => Model[item].Name)
</td>
</tr>
}
</table>
<input type="submit" value="Edit All" />
}
Your view will be rendered as follows, this array based naming convention makes it possible for Defaultbinder to convert it into ICollection as a first parameter of action EditAll
<tr>
<td>
<input name="[0].ResultId" type="text" value="1" />
</td>
<td>
<input name="[0].Name" type="text" value="Pravin" />
</td>
</tr>
<tr>
<td>
<input name="[1].ResultId" type="text" value="2" />
</td>
<td>
<input name="[1].Name" type="text" value="Pradeep" />
</td>
</tr>
If I understand your question correctly,
you want to change your view to be a list of your model object #model List, then using a loop or however you wish to do it, create however many editors you need to for each object
then in your controller your receiving parameter of create will be a list of your model instead too.

Resources