MVC5 ViewModel Not Posting back to Controller - c#

So, I have an issue with a controller/view/viewmodel. It's similar to this issue I think. Basically, I have a viewmodel that I send to a view from my controller. There are items that display and then some additional fields for the user to manipulate before the whole mess is sent back over to a controller post action. When I get the data back in my post, all of the viewmodel is empty.
So, without further ado, here's some code to look at:
ViewModel:
public class ASideReceivingViewModel
{
public PurchaseOrderLine poLine;
public ReceivingItem receivingItem;
public Dictionary<string, string> TankerOrRailcarOptions { get; set; }
public ASideReceivingViewModel()
{
TankerOrRailcarOptions = new Dictionary<string, string>();
TankerOrRailcarOptions.Add("R", "Railcar");
TankerOrRailcarOptions.Add("T", "Tanker");
}
}
Controller Actions:
public ActionResult Receive(string strOrdNo, short? shtLineNo)
{
//if there isn't a selected po line, then shoot them back to the first page
if (strOrdNo == null || !shtLineNo.HasValue) return RedirectToAction("Index");
PurchaseOrderService poService = new PurchaseOrderService();
ReceivingItemService s = new ReceivingItemService(p);
ASideReceivingViewModel vm = new ASideReceivingViewModel();
vm.poLine = poService.GetOpenPurchaseOrderLines().Where(po => po.Ord_no == strOrdNo &&
po.Line_no == shtLineNo).FirstOrDefault();
if (vm.poLine == null) return RedirectToAction("Index");
vm.receivingItem = s.CreateNewReceivingItem(vm.poLine);
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Receive(ASideReceivingViewModel mytestvm)
{
if (ModelState.IsValid && mytestvm.receivingItem != null)
{
ReceivingItemService s = new ReceivingItemService(p);
s.Update(mytestvm.receivingItem);
return RedirectToAction("Index");
}
return View(mytestvm);
}
View:
#model FSIApps.Presentation.Models.ASideReceivingViewModel
<div class="row">
#{Html.RenderPartial("POLineDetails", Model.poLine);}
</div>
#using (Html.BeginForm("Receive", "Receiving", FormMethod.Post))
{
#Html.HiddenFor(model => model.receivingItem.Id)
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="row">
#Html.AntiForgeryToken()
<div class="col-md-6">
<div class="form-group">
<label for="receivingItem_Batch_number">Batch Number</label>
#Html.TextBoxFor(model => model.receivingItem.Batch_number, new { #class = "form-control" })
<span class="help-block">*Also the Vendor Lot Number on the BOL</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="receivingItem_Qty_received">Qty Received</label>
#Html.TextBoxFor(model => model.receivingItem.Qty_received, new { #class = "form-control" })
<span class="help-block">*Qty shown on BOL</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="receivingItem_Carrier">Carrier</label>
#Html.TextBoxFor(model => model.receivingItem.Carrier, new { #class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="receivingItem_">Tanker or Railcar</label>
#Html.DropDownListFor(m => m.receivingItem.Tanker_or_railcar, new SelectList(Model.TankerOrRailcarOptions, "Key", "Value", Model.receivingItem.Tanker_or_railcar), new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="receivingItem_Railcar_number">Railcar Number</label>
#Html.TextBoxFor(model => model.receivingItem.Railcar_number, new { #class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="receivingItem_Manifest_number">Manifest Number</label>
#Html.TextBoxFor(model => model.receivingItem.Manifest_number, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
}
I don't necessarily care about the data I send to the partial view, but when I post back the regular form I get nothing set in the ViewModel. In the other post they talk about how that's an issue with naming the parameter sent back to the controller, but no combination of setting the value in my #Html.BeginForm() seems to do the trick.
Anyone have any advice for me here?
Edited:

To use the automatic model binding, you should use properties instead of fields in the view model. Hopefully this does the trick:
public class ASideReceivingViewModel
{
public PurchaseOrderLine poLine { get; set; };
public ReceivingItem receivingItem { get; set; };
...
}

Related

Text fields name error that coming from Viewmodel in form MVC

i am using viewModel in text fields but the name of the model fields is not actual in browser viewsource. in browser viewsource it is showing model field name with viewmodel name like name="ResetPasswordModel.NewPassword" and also field id is showing like name so how i can fix this . i have added browser viewsource code and actual code Please review it. i hope you understand my question thanks.
ViewModel
public class ProductViewModel
{
public User UserDetails { get; set; }
public ResetPasswordModel ResetPasswordModel { get; set; }
}
public class ResetPasswordModel
{
public string CurrentPassword{ get; set; }
public string NewPassword { get; set; }
}
View
#model ProjectName.Models.ProductViewModel
#using (Html.BeginForm("ActionName", "Controller", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.UserDetails.UserID)
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Current Password</label>
#Html.TextBoxFor(model => model.ResetPasswordModel.CurrentPassword, new { #class = "form-control", placeholder = "Current Password" })
#Html.ValidationMessageFor(model => model.ResetPasswordModel.CurrentPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">New Password</label>
#Html.TextBoxFor(model => model.ResetPasswordModel.NewPassword, new { #class = "form-control", placeholder = "New Password" })
#Html.ValidationMessageFor(model => model.ResetPasswordModel.NewPassword, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
Browser ViewSource
you can see their it is not showing model fields names right
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Current Password</label>
<input class="form-control" name="ResetPasswordModel.CurrentPassword" placeholder="Current Password" data-val="true" data-val-required="The Current Password field is required." id="ResetPasswordModel_CurrentPassword" type="text" value="" />
<span class="field-validation-valid text-danger" data-valmsg-for="ResetPasswordModel.CurrentPassword" data-valmsg-replace="true"></span>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">New Password</label>
<input class="form-control" name="ResetPasswordModel.NewPassword"
placeholder="New Password" id="ResetPasswordModel_NewPassword" type="text" data-val="true" data-val-maxlength="Maxmimum 40 characters allowed" data-val-maxlength-max="40" data-val-minlength="Minimum 8 characters required for password" data-val-minlength-min="8" data-val-required="The Password field is required" value="" />
<span class="field-validation-valid text-danger" data-valmsg-for="ResetPasswordModel.NewPassword" data-valmsg-replace="true"></span>
</div>
</div>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ActionName(ResetPasswordModel ResetPass)
{
if (ModelState.IsValid)
{
}
return View();
}
The problem is, in your View your model is: ProductViewModel, but in your controller, you are expecting: ResetPasswordModel.
This is not right, either change the controller to accept: ProductViewModel
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ActionName(ProductViewModel productViewModel)
{
if (ModelState.IsValid)
{
}
return View();
}
In this case, this the input with name=ResetPasswordModel.NewPassword would be correctly bound to your model.
Or change the Model in your view:
#model ResetPasswordModel
#using (Html.BeginForm("ActionName", "Controller", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.UserDetails.UserID)
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">Current Password</label>
#Html.TextBoxFor(model => model.CurrentPassword, new { #class = "form-control", placeholder = "Current Password" })
#Html.ValidationMessageFor(model => model.CurrentPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label">New Password</label>
#Html.TextBoxFor(model => model.NewPassword, new { #class = "form-control", placeholder = "New Password" })
#Html.ValidationMessageFor(model => model.NewPassword, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
In this case the input name would be: NewPassword
you can set name property like this:
#Html.TextBoxFor(model => model.ResetPasswordModel.NewPassword, new { #class = "form-control", placeholder = "New Password" , Name="NewPassword"})

Empty POST model argument when using EditorFor

I am trying to submit a form that incorporates an #Html.EditorFor element. If I remove the EditorFor element, my POST controller argument passes data correctly, but once implemented, my entire model argument shows as null in the POST controller.
Here's the model I'm trying to pass:
public class Checkout
{
public int CheckoutID { get; set; }
public string Requestor { get; set; }
public DateTime? DateRequested { get; set; }
public List<CheckoutReceiver> Receivers { get; set; }
}
The form element on page:
#model PRI.Models.Checkout
#using (Html.BeginForm("CreateCheckout", "API/CheckoutRequest", FormMethod.Post, new { id = "pri-form" }))
{
<div id="checkout-request">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div id="checkout-info" class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(m => m.CheckoutID)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(m => m.Receivers)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input id="create-checkout-submit" type="submit" value="Confirm transfer" class="btn btn-danger right" style="margin: 10px;" />
</div>
</div>
</div>
</div>
}
If I remove the #Html.EditorFor(m => m.Receivers), and add data to the #Html.TextBoxFor(m => m.CheckoutID) then that passes correctly to my Post Controller, so obviously my EditorFor is messing things up:
Here's the POST controller (i put a breakpoint right after it enters this so I can check the checkout argument):
[System.Web.Http.HttpPost]
[ValidateAntiForgeryToken]
[System.Web.Http.ActionName("CreateCheckout")]
public Checkout Create(Checkout checkout)
{
var request = new Checkout();
return request;
}
Here's my CheckoutReceiver Editor template (removed some input elements for brevity):
#model PRI.Models.CheckoutReceiver
#using (Html.BeginCollectionItem("Receivers"))
{
<div class="form-horizontal">
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.CheckoutID)
<h4 class="contact-header">#Model.ContactType</h4>
<div class="form-group">
<div class="col-md-5">
<span class="form-header">Last Name</span>
#Html.TextBoxFor(model => model.LastName, new { #class = "box-customer form-control ignore", placeholder = "Last name" })
</div>
<div class="col-md-5">
<span class="form-header">First Name</span>
#Html.TextBoxFor(model => model.FirstName, new { #class = "form-control ignore", placeholder = "First name" })
</div>
<div class="col-md-2">
<span class="form-header">Middle Initial</span>
#Html.TextBoxFor(model => model.MiddleInitial, new { #class = "form-control ignore", placeholder = "M.I." })
</div>
</div>
</div>
}
Where am I going wrong, and why is my EditorFor causing my Checkout POST argument to be null on submit?
Thanks!
Maybe you should check this question. You should add an editor for an
IEnumerable<CheckoutReceiver> instead of an editor for CheckoutReceiver.

Session is bleeding over to another customer

I am storing a name and address in session in a static session class. When a customer pulls up the payment screen, I prefill the form with the name and address. If customer A pulls up the credit card screen and then customer B pulls up the same screen, customer B has the name and address of customer A.
I'm thinking this is happening due to a 'static' session class? If this is the case, how do I avoid this?
Here is my MySession class:
public static class MySession
{
public static string BranchNumber { set; get; }
public static string AccountNumber { set; get; }
public static string Name { set; get; }
public static string CustomerEmail { get; set; }
public static string Street { get; set; }
public static string Zip { get; set; }
public static string Zip4 { get; set; }
}
And my form:
#model SssMobileIInquiry.Models.HomeModels.CreditCard
#{
ViewBag.Title = "Credit Card Payment";
}
<div class="container">
#using (Html.BeginForm("SubmitCreditCardCharge", "Home", FormMethod.Post))
{
<h4>Credit Card Payment</h4>
<div class="row">
<div class="col-sm-3">
Name
</div>
<div class="col-sm-9 focus">
#Html.TextBoxFor(m => m.NameOnCard, new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-sm-3">
Street
</div>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.Street, new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-sm-3">
Zip Code
</div>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.ZipCode, new { #class = "form-control", #maxlength = "9" })
</div>
</div>
<div class="row">
<div class="col-sm-3">
Card Number
</div>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.CardNumber, new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-sm-3">
Expiration Date
</div>
<div class="col-sm-9 datefieldsmall">
#Html.TextBoxFor(m => m.ExpirationDateMonth, new { #class = "form-control", #maxlength = "2", #placeholder = "MM" })
</div>
<div class="col-sm-9 datefieldsmall">
#Html.TextBoxFor(m => m.ExpirationDateYear, new { #class = "form-control", #maxlength = "2", #placeholder = "YY" })
</div>
</div>
<div class="row">
<div class="col-sm-3">
CVV Number
</div>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.PinNumber, new { #class = "form-control", #maxlength = "4" })
</div>
</div>
<div class="row">
<div class="col-sm-3">
Amount
</div>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.PaymentAmount, new { #class = "form-control", #maxlength = "7" })
</div>
</div>
<div class="warning">
#Html.ValidationMessageFor(m => m.PaymentAmount)
</div>
<div class="row">
<input id="submitpayment" class="btn btn-primary btn-block buttonx accountinfobutton" type="submit" value="Submit" />
</div>
}
#using (Html.BeginForm("AccountInfo", "Home", FormMethod.Post))
{
<div class="row">
<input id="submitpayment" class="btn btn-primary btn-block buttonx accountinfobutton" type="submit" value="Account" />
</div>
}
</div>
And my ActionResults:
public ActionResult CreditCard()
{
if (MySession.CorporationId == Guid.Empty || string.IsNullOrEmpty(MySession.AccountNumber))
{
return View("Index");
}
var model = new Models.HomeModels.CreditCard();
model.NameOnCard = MySession.Name;
model.Street = MySession.Street;
model.ZipCode = MySession.Zip;
model.PaymentAmount = MySession.TotalBalance.Contains("-") ? "" : MySession.TotalBalance;
if (MySession.BudgetBalance.GetNumericValue() > 0 && MySession.BudgetRate.GetNumericValue() > 0)
{
model.PaymentAmount = MySession.BudgetBalance;
}
return View("CreditCard", model);
}
I am populating my model with MySession:
model.NameOnCard = MySession.Name;
model.Street = MySession.Street;
model.ZipCode = MySession.Zip;
I'm not sure why the customer information is being displayed for another account logged in. Any ideas would be greatly appreciated.
Thanks for the help!
You're using static. Static means there is only 1 copy of the class and is shared throughout the application. You need to change it so it isn't static and you must instantiate this for each user.

ASP.NET MVC 4 Model binding issue

The issue is that, model binding doesn't bind one of the properties of ViewModel.
I have a ViewMode, HomeIndexViewModel.
One of the properties, ExcludeClientsWithoutAddress doesn't get bound in controller.
Fiddler shows GET request as such (without ExcludeClientsWithoutAddress)
GET /Home/searchByClient?db=dev&fileNumber=&firstName=xxx&includeContacts=true HTTP/1.1
For some reason, Other properties (FileNumber, FirstName, LastName, IncludeContacts, and File) get bound correctly.
What am I missing here?
namespace CertifiedMail.Web.Mvc4.OneOffs.Models
{
public class HomeIndexViewModel
{
[DisplayName("File #")]
public string FileNumber { get; set; }
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("Include Contact")]
public bool IncludeContacts { get; set; }
[DisplayName("Exclude Clients Without Address")]
public bool ExcludeClientsWithoutAddress { get; set; }
public HttpPostedFileBase File { get; set; }
}
}
Within Controller,
[System.Web.Mvc.HttpGet]
public string SearchByClient([FromUri]HomeIndexViewModel model)
{
IEnumerable<SearchResult> searchResults = new List<SearchResult>();
SearchByArgs args = BuildSearchByArg(model);
if (string.IsNullOrWhiteSpace(model.FileNumber))
{
if (!string.IsNullOrWhiteSpace(model.FirstName) || !string.IsNullOrWhiteSpace(model.LastName))
searchResults = ClientSearchDataAccess.SearchByClientName(args);
}
else
searchResults = ClientSearchDataAccess.SearchByClientNumber(args);
return JsonConverter.SerializeSearchResults(searchResults);
}
Here is the View.
<div class="col-sm-5 searchPanel">
<div class="panel panel-default glowGridPanel">
<div class="panel-body searchPanelBody">
<div class="row">
#using (Html.BeginForm("SearchByClient", "Home",
new { db = #Request.QueryString["db"] },
FormMethod.Get,
new { id = "searchByClientForm", #class = "form-horizontal" }))
{
<fieldset>
<legend>
Search by Client
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</legend>
#{
var labelAttributes = new { #class = "col-sm-4 control-label" };
}
<div class="form-group">
#Html.LabelFor(m => m.FileNumber, labelAttributes)
<div class="col-sm-8">
#Html.TextBoxFor(m => m.FileNumber, new { #class = "form-control input-sm", ng_model = "fileNumber" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.FirstName, labelAttributes)
<div class="col-sm-8">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control input-sm", ng_model = "firstName" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.LastName, labelAttributes)
<div class="col-sm-8">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control input-sm", ng_model = "lastName" })
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col-sm-offset-3">
<div class="checkbox">
Include contacts in search result?
#Html.CheckBoxFor(m => m.IncludeContacts, new { id = "includeContactsCheckBox", ng_model = "includeContacts" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col-sm-offset-3">
Exclude Clients without Address?
<div class="checkbox">
#Html.CheckBoxFor(m => m.ExcludeClientsWithoutAddress,
new { id = "excludeClientsWithoutAddressCheckBox", ng_model = "excludeClientsWithoutAddress" })
</div>
</div>
</div>
<button type="button" class="btn btn-primary pull-right submitButton"
ng-click="addSearchResultToGrid()"
ng-disabled="loadingSearch">
Search by Client
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
<div id="loadingSearch" ng-show="loadingSearch"></div>
</button>
</fieldset>
}
</div>
<div class="row strike">
<h3>
<span class="label label-default">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
OR
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</span>
</h3>
</div>
<div class="row">
#using (Html.BeginForm("Upload", "Home",
new { db = #Request.QueryString["db"] },
FormMethod.Post, new { id = "uploadFileForm", enctype = "multipart/form-data" }))
{
<fieldset>
<legend>Search by Uploading File</legend>
<div class="input-group">
<input type="file" class="form-control" name="file" id="file" />
<span class="input-group-btn">
<button class="btn btn-primary" type="submit">
Upload File
<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>
</button>
</span>
</div>
</fieldset>
}
</div>
</div>
</div>
</div>
Your Fiddler request shows what is emitted from the browser. It isn't sending your ExcludeClientsWithoutAddress property.
Since this property is not marked nullable bool? it is being assigned a default value in binding.
You have these inputs as ng_model which suggests your Angular code is not sending this field.

ASP .Net MVC Form not calling controller on submit

I am having trouble getting my view to call the post method in my MVC Controller. When I click on the submit button, it does not call the Create method. I add a breakpoint, but it never gets to the code. I am assuming some error, but not sure how to see the error message.
Here is the View:
#model PersonViewModel
#{
ViewBag.Title = "Register";
}
#using (Html.BeginForm(PeopleControllerAction.Create, ControllerName.People, FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal row">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
</div>
<div class="row panel radius">
<div class="medium-2 columns">
<h3>Contact Information</h3>
</div>
<div class="medium-10 columns">
<div class="row">
<div class="medium-6 columns">
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
</div>
// more fields removed for brevity
<div class="row">
<div class="form-group">
<div>
<input type="submit" value="Submit" class="button" />
</div>
</div>
</div>
}
Here is the controller:
public class PeopleController : Controller
{
private IPersonService context { get; set; }
public PeopleController(IPersonService context)
{
this.context = context;
}
// POST: People/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "FirstName,LastName,Age,Email,Phone,City,State,HopeToReach,Story,Goal,Image")] PersonViewModel person)
{
if (ModelState.IsValid)
{
try
{
person.ImagePath = ImageUploader.UploadImage(person.Image);
}
catch (ArgumentException e)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);
}
var id = await context.AddAsync(person);
return RedirectToAction(PeopleControllerAction.Confirmation);
}
return View(person);
}
}
This was resolved. The action in question did not have a route. I am using attribute routing.

Categories