All model and Formcollection values are null, blank or don't exist in Firefox or Chrome - asp.net-mvc

During debugging, my MVC model and Formcollection are blank with no values in FireFox (15) or Chrome (latest version).
During debugging using IE (9), I can see these values just fine.
Do you know what the solution is for this? This is very serious for public facing web sites not being able to do any programming angainst these browsers.
Here is my View...
#model PDFConverterModel.ViewModels.ViewModelTemplate_Guarantors
#{
ViewBag.Title = "BHG :: PDF Generator";
}
<h2>#ViewBag.Message</h2>
<div>
<table style="width: 1000px">
<tr>
<td colspan="5">
<img alt="BHG Logo" src="~/Images/logo.gif" />
</td>
</tr>
#using (Html.BeginForm("ProcessForm", "Home", FormMethod.Post))
{
<tr>
<td>
#(Html.Kendo().IntegerTextBox()
.Name("LoanID")
.Placeholder("Enter Loan ID")
)
</tr>
<tr>
<td>#Html.LabelFor(model => model.LoanType)
#Html.DisplayFor(model => model.LoanType)
</td>
<td>
<label for="ddlDept">Department:</label>
#(Html.Kendo().DropDownList()
.Name("ddlDept")
.DataTextField("DepartmentName")
.DataValueField("DepartmentID")
.Events(e => e.Change("Refresh"))
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetDepartments", "Home");
});
})
)
</td>
</tr>
if (Model.ShowGeneratePDFBtn == true)
{
if (Model.ErrorT == string.Empty)
{
<tr>
<td colspan="5">
<u><b>#Html.Label("Templates:")</b></u>
</td>
</tr>
<tr>
#for (int i = 0; i < Model.Templates.Count; i++)
{
<td>
#Html.CheckBoxFor(model => Model.Templates[i].IsChecked)
#Html.DisplayFor(model => Model.Templates[i].TemplateId)
</td>
}
</tr>
}
else
{
<tr>
<td>
<b>#Html.DisplayFor(model => Model.ErrorT)</b>
</td>
</tr>
}
if (Model.ErrorG == string.Empty)
{
<tr>
<td colspan="5">
<u><b>#Html.Label("Guarantors:")</b></u>
</td>
</tr>
<tr>
#for (int i = 0; i < Model.Guarantors.Count; i++)
{
<td>
#Html.CheckBoxFor(model => Model.Guarantors[i].isChecked)
#Html.DisplayFor(model => Model.Guarantors[i].GuarantorFirstName) #Html.DisplayFor(model => Model.Guarantors[i].GuarantorLastName)
</td>
}
</tr>
}
else
{
<tr>
<td>
<b>#Html.DisplayFor(model => Model.ErrorG)</b>
</td>
</tr>
}
}
<tr>
<td colspan="3">
<input type="submit" name="submitbutton" id="btnRefresh" value='Refresh' />
</td>
#if (Model.ShowGeneratePDFBtn == true)
{
<td>
<input type="submit" name="submitbutton" id="btnGeneratePDF" value='Generate PDF' />
</td>
}
</tr>
<tr>
<td colspan="5">
#Model.Error
</td>
</tr>
}
</table>
</div>
<script type="text/javascript">
$('btnRefresh').on('click', '#btnRefresh', function () {
Refresh();
});
function Refresh() {
var LoanID = $("#LoanID").val();
if (LoanID != "") {
document.forms[0].submit();
}
else {
alert("Please enter a LoanId");
}
}
</script>

I know this is a very old question, but answering this might help people like who are struggling with this issue.
I had a similar issue. The problem lies here:
<table style="width: 1000px">
<tr>
<td colspan="5">
<img alt="BHG Logo" src="~/Images/logo.gif" />
</td>
</tr>
#using (Html.BeginForm("ProcessForm", "Home", FormMethod.Post))
{
<tr>
<td>
#(Html.Kendo().IntegerTextBox()
.Name("LoanID")
.Placeholder("Enter Loan ID")
)
</td>
</tr>
}
</table>
After begin form there are <tr> tags directly! Browsers like chrome and mozilla get confused in such cases. The <table> tag should be inside the form. If we look at your code, which was exactly what I had done, <table> tag was before #using Html.BeginForm.
Internet Explorer somehow understands this, but the other browsers don't.
When I did an inspect element I found that there was a form tag within each <tr> tag and it always returned FormCollection as null. Simply defining <table> within form solved my problem.
So here's how it should be:
<table style="width: 1000px">
<tr>
<td colspan="5">
<img alt="BHG Logo" src="~/Images/logo.gif" />
</td>
</tr>
<tr><td>
#using (Html.BeginForm("ProcessForm", "Home", FormMethod.Post))
{
<table>
<tr>
<td>
#(Html.Kendo().IntegerTextBox()
.Name("LoanID")
.Placeholder("Enter Loan ID")
)
</td>
</tr>
</table>
}
</td></tr>
</table>

I just found out what the issue is by experimneting.
The Telerik MVC widgets don't emit any FormCollection data!!!!
Only EditorFor and TextBoxFor emit these values, plus the input buttons.
What good are these widgets if I can't use the FormCollection values from them???? Especially the DropDownList where I can retrireve data and need the selected value to pass onto other methods.

(This would be better suited as comment, but I can't comment yet)
For future reference, here's a spec (W3C might have something different) for what gets submitted when a form is submitted:
http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#category-submit
You can look at whatever HTML was generated to make sure it gets submitted. You could also use something like Fiddler to look at the Http request

Related

Partial View linkage to controller and model [duplicate]

This question already has answers here:
#Html.Action in Asp.Net Core
(10 answers)
Closed 6 years ago.
I am new to .Net and MVC and I seem to hit a problem that I can´t fix. I am trying to follow a couple of tutorials but I have failed when it comes to partial views. I looked up a lot of answers here and on different websites and still nothing works. I can´t figure out what I am doing wrong.
This is my partial controller:
public class PartialController : Controller
{
public ActionResult _PartialView()
{
var model = new Partial();
model.Count = 2;
return PartialView(model);
}
}
And this is my Partial View:
#model WebApplication1Tutorial.Models.Partial
<div>
The magic number is:
#Html.DisplayFor(model => model.Count)
</div>
I call this view in Index.cshtml by the following command:
<div>
#Html.Partial("/Views/Partial/_PartView.cshtml",new Partial())
</div>
And finally this is the model:
public class Partial
{
public int Count { get; set; }
}
Everything that I tried comes up with the webpage displaying the text and the number 0. I really have no idea what else to do. I know it is something easy but I can´t see it.
Thanks for the help.
Edit. The code for the index view:
#model MovieGenreViewModel
#{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-controller="Movies" asp-action="Index" method="get">
<p>
<select asp-for="movieGenre" asp-items="Model.genres">
<option value="">All</option>
</select>
Title: <input type="text" name="SearchString" >
<input type="submit" value="Filter" />
</p>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.movies[0].Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.movies[0].Price)
</th>
<th>
#Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
</th>
<th>
#Html.DisplayNameFor(model => model.movies[0].Title)
</th>
<th>
#Html.DisplayNameFor(model => model.movies[0].Rating)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.movies) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rating)
</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>
<div>
#{ Html.RenderAction("_PartialView"); }
</div>
When you pass your partial like with the #Html.Partial, you also pass a new Model and the _PartialView() method is not invoked so the model is not populated with the value 2.
You could use #Html.Action helper:
<div>
#Html.Action("/Views/Partial/_PartView.cshtml")
</div>

Why do textboxes not clear out after clearing out Model

I have a form which is submitted via ajax to the Controller. The Controller collects the data from the Model and then creates a new ViewModel and passes it to the partial view which is then updated on the Client.
The problem is that the textboxes are not cleared out as expected. The message arrives in the View as expected, so it doesn't make sense that the TextBoxes are not cleared out.
Yet it seems to be a browser issue as this is the resulting HTML, which note, does not have anything in the value:
<input id="Address_Address1" name="Address.Address1" type="text" value="" />
Yet the user sees the value that was priorly entered.
Here is the controller:
//Process Order Here
//This should clear out the ViewModel.
order = new OrderViewModel();
order.Message = "Report Added to your cart";
return PartialView("_NewOrderPartial", order);
This is the partial View:
#model NTC.PropertySearch.Models.OrderViewModel
#using (Ajax.BeginForm("NewOrder", "Order", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "neworder" }))
{
<div id="neworder">
<table>
<tr>
<th style="width: 300px;">
<h3>Enter property address below</h3>
</th>
<th style="width: 30px;"></th>
<th style="width: 300px;">
<h3>Choose your report below</h3>
</th>
</tr>
<tr>
<td>
<div class="form">
<table>
<tr>
<td>
#Html.LabelFor(m => m.Address.Address1)
</td>
<td>
#Html.TextBoxFor(m => m.Address.Address1)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.Address1)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.Address2)
</td>
<td>
#Html.TextBoxFor(m => m.Address.Address2)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.Address2)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.City)
</td>
<td>
#Html.TextBoxFor(m => m.Address.City)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.City)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.State)
</td>
<td>
#Html.TextBoxFor(m => m.Address.State)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.State)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Address.ZipCode)
</td>
<td>
#Html.TextBoxFor(m => m.Address.ZipCode)
</td>
<td>
#Html.ValidationMessageFor(m => m.Address.ZipCode)
</td>
</tr>
</table>
<input type="submit" value="Add Report" />
#Html.DisplayFor(m=> m.Message)
</div>
</td>
</tr>
</table>
</div>
The reason for this is because the Html helpers such as TextBox are first looking at the ModelState when binding their values and only after that in the View model. This often happens when people attempt to modify/clear some value to the view model in an HttpPost controller action. The corresponding view will use the initial POSTed value and not the value in the view model.
You should clear the ModelState as well in your controller action:
ModelState.Clear();
order = new OrderViewModel();
Alternatively if you do not want to clear the entire ModelState (although in your case this seems to be the case as you are reinitializing the entire view model) you could clear only some properties that you intend to modify:
ModelState.Remove("SomeProperty");
viewModel.SomeProperty = "some new value";

Trying to figure out Ajax.BeginForm

I have a view in 2 sections.
The top section I input fields and submit to save them.
In the second section I have an autocomplete textbox. I select an item in autocomplete, and when I click submit I want to add that item to a datatable.
So for the first part when I click submit I save the details via a HttpPost method on the controller.
For the second part I intend to save it via an Ajax call for the controller and then bring back a partial view with the results. I have not coded the partial view yet, that is next.
Now I am new to Ajax.BeginForm and I am struggling with it.
I was hoping that the submit button inside the Ajax.BeginForm would only apply to that part of the form.
But in fact it calls the HttpPost method for the whole form.
So how do I fix this?
My view looks like;
#using ITOF.HtmlHelpers
#model ITOF.Models.OngoingContractViewModel
#{
ViewBag.Title = "EditOngoingContractDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("EditOngoingContractDetails", "Contract", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Contract.ContractId)
<h1>Edit Ongoing Contract Details</h1>
<fieldset>
<legend>#Model.Contract.Heading</legend>
<p>Where you see <span class="error">*</span> you must enter data.</p>
<table>
<tr>
<td style="text-align: right">
#Html.LabelFor(model => model.Contract.EndDate)
</td>
<td>
#Html.EditorFor(model => model.Contract.EndDate)
</td>
</tr>
<tr>
<td style="text-align: right">
#Html.LabelFor(model => model.Contract.Organogramme)
</td>
<td>
<input type="file" id="PDF" name="file" />
#Html.HiddenFor(model => model.Contract.Organogramme)
</td>
</tr>
#if (!string.IsNullOrWhiteSpace(Model.Contract.Organogramme))
{
<tr>
<td></td>
<td>
The current organogramme is <span class="HighlightTextRed">#Model.GetOrganogrammeName()</span>
for the contract <span class="HighlightTextRed">#Model.Contract.ContractName</span><br/>
Click here to see the last saved organogramme
</td>
</tr>
}
<tr>
<td style="text-align: right">
#Html.LabelFor(model => model.Contract.AssistantRLOManagerId)
</td>
<td>
#Html.DropDownListFor(model => model.Contract.AssistantRLOManagerId, Model.AssistantRloManagerSelectList, "--N/A--")
</td>
</tr>
#if (this.TempData["SuccessMessage"] != null)
{
<tr>
<td colspan="2" class="success">#this.TempData["SuccessMessage"].ToString()</td>
</tr>
}
<tr>
<td colspan="2" style="padding-top: 20px; text-align: center;"><input type="submit" value="Save" /></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Add an existing Site to this contract: </legend>
#using (Ajax.BeginForm("AddExistingSite", new AjaxOptions { UpdateTargetId = "siteRows" }))
{
<input type="text" name="q" style="width: 800px"
data-autocomplete="#Url.Action("SiteSearch", "DataService", new { contractId = #Model.Contract.ContractId })" />
<input type="submit" value="Add site to contract" />
}
#if (Model.SiteList.Count > 0)
{
<table id="siteDataTable" class="display">
<thead>
<tr>
<th>Main Site?</th>
<th>Type</th>
<th>Address</th>
<th>Map</th>
<th>Telephone</th>
<th>Email</th>
</tr>
</thead>
<tbody id="siteRows">
#foreach (var item in Model.SiteList)
{
<tr id="#item.SiteContract.SiteContractId">
<td>#item.SiteContract.MainSiteFlag</td>
<td>#item.Site.SiteType</td>
<td>#item.Site.Address</td>
<td>#item.Site.MapUrl</td>
<td>#item.Site.Telephone</td>
<td>#item.Site.Email</td>
</tr>
}
</tbody>
</table>
<div class="add_delete_toolbar" />
}
#Html.ListLink("Back to List")
</fieldset>
}
Oh no, you just cannot nest HTML forms. That's not supported. You will have to rethink your design. This really has absolutely nothing to do with ASP.NET MVC and things like Html.BeginForm or Ajax.BeginForm. The HTML specification simply tells you that the <form> tag cannot be nested and if you nest it you will get undefined behavior that could vary between browsers.
For example you could implement the autocomplete functionality using jquery UI autocomplete plugin and get rid of the Ajax.BeginForm.

Html.HiddenFor causing error

When I try to add #Html.HiddenFor(#Model.ID) to my code, I get the following error when access the page:
Compiler Error Message: CS0411: The type arguments for method 'System.Web.Mvc.Html.InputExtensions.HiddenFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
I tried reading MSDN, but the documentation is awful (they don't provide a single code example in the documentation for this method.
Here is my View:
#model CustomerService.Entity.Order
#using CustomerService.Entity
#{
ViewBag.Title = "OrderDetails";
}
<h2>
OrderDetails</h2>
#using (Html.BeginForm("HandleSubmit", "Home", FormMethod.Post))
{
<table border="1">
<tr>
<td>
<b>Order #</b>
</td>
<td>
#Model.ID
</td>
</tr>
<tr>
<td>
<b>Description</b>
</td>
<td>
#Model.Description
</td>
</tr>
<tr>
<td>
<b>Salesperson Name</b>
</td>
<td>
#Model.SalespersonName
</td>
</tr>
</table>
<h3>
Line Items</h3>
<input id="btnAddLineItem" type="submit" name="AddLineItem" value="AddLineItem" />
#Html.HiddenFor(#Model.ID)
<table border="1">
<tr>
<td>
<b>Line Item ID</b>
</td>
<td>
<b>Description</b>
</td>
</tr>
#for (int i = 0; i < #Model.LineItems.Count; ++i)
{
<tr>
<td>
#Model.LineItems[i].ID
</td>
<td>
#Model.LineItems[i].Description
</td>
</tr>
}</table>
}
HiddenFor takes an expression.
#Html.HiddenFor( model => model.ID )
HiddenFor method should get an Expression as a parameter not a value:
#Html.HiddenFor(m => m.ID)
Instead of: #Html.HiddenFor(#Model.ID)
Method signature:
HiddenFor<TModel, TProperty>(HtmlHelper<TModel>,
Expression<Func<TModel, TProperty>>)
In plain text you should give an Expression that gets an "instance" of the type of your model(in this case CustomerService.Entity.Order) and returns the desired property(in this case ID)
MSDN

MVC multiple forms on single view not working

I have 2 forms on a single razor view that open in seperate dialog boxes. The forms are submitted using jquery post..
First form works perfectly but the second form isnt recognised at all and when I try to serializr the data it returns an empty string.
Code below:
#using (Html.BeginForm("SaveElectricReading", "Store", FormMethod.Post, new { id = "frmSaveElectricReading" }))
{
<div id="electricDialog" style="display: none;" title="Electric Readings">
<p>
Please ensure the electric readings have been entered!
</p>
<table width="100%">
<tr>
<th>
Serial:
</th>
</tr>
<tr>
<td>
<input type="text" name="Serial" />
</td>
</tr>
<tr>
<th>
Reading:
</th>
</tr>
<tr>
<td>
<input type="text" name="Reading" />
</td>
</tr>
<tr>
<th>
Comment:
</th>
</tr>
<tr>
<td>
<div class="textwrapper">
<textarea rows="5" cols="10" name="Comment"></textarea>
</div>
</td>
</tr>
</table>
</div>
}
#using (Html.BeginForm("SaveWaterReading", "Store", FormMethod.Post, new { id = "myform" }))
{
<div id="waterDialog" style="display: none;" title="Water Readings">
<p>
Please ensure the water readings have been entered!
</p>
<table width="100%">
<tr>
<th>
Serial:
</th>
</tr>
<tr>
<td>
<input type="text" name="WaterSerial" />
</td>
</tr>
<tr>
<th>
Reading:
</th>
</tr>
<tr>
<td>
<input type="text" name="WaterReadingsdfsdf" />
</td>
</tr>
<tr>
<th>
Comment:
</th>
</tr>
<tr>
<td>
<div class="textwrapper">
<textarea rows="5" cols="10" name="WaterComment"></textarea>
</div>
</td>
</tr>
</table>
</div>
}
function showWaterDialog() {
var $dialog = $('#waterDialog').dialog({
autoOpen: false,
modal: true,
width: 400,
height: 400,
buttons: {
Submit: function () {
// $('#frmCreateStore').submit();
var data = $('#frmSaveWaterReading');
$.post("/Store/SaveWaterReading",
$("#frmSaveWaterReading").serialize(),
function () {
$("#waterDialog").dialog("close");
});
//$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$dialog.dialog('open');
}
In the jquery function for showing the dialog with the form in it, I needed to add that dialog content to the second form on the page as follows:
$("#waterDialog").parent().appendTo($("form").eq(1)[0]);

Resources