why ActionResult method parameter is null in asp.net MVC? [duplicate] - c#

This question already has answers here:
Asp.Net MVC: Why is my view passing NULL models back to my controller?
(2 answers)
Closed 5 years ago.
I'm trying to send a form to ActionResult method but it is null always. In fact, I got the error Value cannot be null. but I don't know why I got it the error.
Here is ActionResult code and my view.
public class VocabularyController : Controller
{
private VocabContext _context;
public VocabularyController()
{
_context = new VocabContext();
}
// GET: Vocabulary
[Route("New")]
public ActionResult New()
{
return View();
}
[HttpPost]
public ActionResult Save(Vocabulary word)
{
if (ModelState.IsValid)
{
_context.Vocabularies.Add(word);
_context.SaveChanges();
}
return RedirectToAction("dashboard", "Home");
}
}
==============================
#model EnglishTest.Models.Vocabulary
#{
ViewBag.Title = "New";
}
<div class="row">
<div class="col-lg-12">
<div class="element-wrapper">
<h6 class="element-header">New Word Form</h6>
<div class="element-box">
#using (Html.BeginForm("Save", "Vocabulary", FormMethod.Post))
{
<div class="form-group">
#Html.LabelFor(m => m.Word)
#Html.TextAreaFor(m => m.Word, new { #class = "form-control", #placeholder = "Word" })
#Html.ValidationMessageFor(m => m.Word)
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.LabelFor(m => m.Defination)
#Html.TextAreaFor(m => m.Defination, new { #class = "form-control", #placeholder = "Definition" })
#Html.ValidationMessageFor(m => m.Defination)
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.LabelFor(m => m.Synonym)
#Html.TextAreaFor(m => m.Synonym, new { #class = "form-control", #placeholder = "Synonym" })
#Html.ValidationMessageFor(m => m.Synonym)
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.LabelFor(m => m.PersianTranslate)
#Html.TextAreaFor(m => m.PersianTranslate, new { #class = "form-control", #placeholder = "Persian Translation" })
#Html.ValidationMessageFor(m => m.PersianTranslate)
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.LabelFor(m => m.Examples)
#Html.TextAreaFor(m => m.Examples, new { #class = "form-control", #placeholder = "Examples" })
#Html.ValidationMessageFor(m => m.Examples)
</div>
</div>
</div>
#Html.HiddenFor(m => m.Id)
<div class="form-buttons-w"><button class="btn btn-primary" type="submit"> Save</button></div>
}
</div>
</div>
</div>
</div></div>
==============================
public class Vocabulary
{
public int Id { get; set; }
[Required]
public string Word { get; set; }
[Required]
public string Defination { get; set; }
[Required]
public string Synonym { get; set; }
[Required]
public string PersianTranslate { get; set; }
[Required]
public string Examples { get; set; }
}

I Changed the input parameter to my model name, it works fine.
public ActionResult Save(Vocabulary vocabulary)

Specify a post to the form:
#using (Html.BeginForm("Save", "Vocabulary", FormMethod.Post))
Also the second # is not requried:
Html.BeginForm("Save", "Vocabulary", FormMethod.Post)

Related

How to get a CheckBox value in MVC C#

This is my view.
I'm starting with MVC C#.
Sorry if this is an a very easy question.
I'm trying to get a CheckBox value from the view. The idea is put some checkboxes on the view, convert these values to Int32, to concatenate on a string entity for afterlly save in my DB.
The checkboxes should not be linked to the model.
Could someone explain me how to do it and how to link the checkbox to the controller? I'm very confused.
This is my model.
namespace Crossdock.Models{
public class Roles
{
[Key]
[Column(Order = 0)]
public int RolID { get; set; }
[Display(Name = "Tipo de Usuario")]
public string Descripcion { get; set; }
[Display(Name = "Permisos")]
public string Permisos { get;set;}
//Permisos a validar por Área
//Guías
public bool GeneracionGuias { get; set; }
//CEDIS
public bool RecepcionPaquetes { get; set; }
public bool CrossdockTemporal { get; set; }
//Administración
public bool Catalogos { get; set; }
}
}
This is my controller code. Here is where i need parse the bool values from the model to int/string and concatenate for save on "Descripcion" string field.
// GET: Roles/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Roles cl)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Index");
}
var rl = new Roles
{
RolID = 0,
Descripcion=cl.Descripcion,
Permisos=cl.Permisos,
};
objRol.Alta_Roles(rl);
return RedirectToAction("Index", new { area = "" });
}
This is my Create View.
#model Crossdock.Models.Roles
#{
ViewBag.Title = "Create";
}
<hr />
<h1>Registrar Nuevo Perfil de Permisos</h1>
<hr />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Descripcion, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Descripcion, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Descripcion, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Permisos, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Permisos, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Permisos, "", new { #class = "text-danger" })
</div>
</div>
<br />
<div class="container">
<div class="row justify-content-center">
<div class="col-4">
<h3>
Guías
</h3>
<span> | Generación de Guías: </span> #Html.CheckBoxFor(m => m.GeneracionGuias, true)
</div>
<div class="col-4">
<h3>
CEDIS
</h3>
<span> | Recepción de Paquetes: </span> #Html.CheckBoxFor(m => m.RecepcionPaquetes, false)
<br />
<span> | Crossdock Temporal: </span> #Html.CheckBoxFor(m => m.CrossdockTemporal, false)
</div>
<div class="col-4">
<h3>
Administración
</h3>
<span> | Catálogos: </span> #Html.CheckBoxFor(m => m.Catalogos, false)
</div>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Registrar" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
<br />
#Html.ActionLink("Regresar", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

ASP.NET core all model values are null when passing a model to the view

Goal: I have a page that I want to have a return url passed through the model of the view so upon completion of the form, it will return to the previous url. The page is a address validation and add it to the account as a saved address.
Flow of the page: You are presented with an address form to fill out. on completion, you will have a button that will call to a controller method that will verify with FedEx via API, and then if valid, it will let you save the address.
Issue: once you press the Verify Address button, it seems to have an issue with sending the form data to the controller.
HTTPGET:
public ActionResult AddShippingAddress(string strReturnURL)
{
// get states
ViewBag.states = GetStates();
DeliveryAddressModel model = new DeliveryAddressModel();
model.strReturnAddress = strReturnURL;
return View(model);
}
AddShippingAddress.chshtml
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
#{
ViewBag.Title = "Shipping Address";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
<partial id="ValidateAddress"></partial>
#using (Html.BeginForm())
{
<h4>Shipping Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<h5>Name</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Attention To</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strAttnTo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street 2</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>City</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.states;
}
<div class="form-group">
<h5>State</h5>
<div class="col-md-10">
#Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State.IntStateId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<h5>Zip</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strZip, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strZip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Phone Number</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strPhoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strPhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Set as Default</h5>
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.blnIsDefault)
#Html.ValidationMessageFor(model => model.blnIsDefault, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal"
data-url="#Url.Action("GetValidationOnAddress", new { model = Model })">
Verify Address
</button>
</div>
</div>
}
</div>
<script>
$(function () {
var PlaceHolderElement = $('#ValidateAddress');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
//$('#ValidateAddress').modal('show');
})
})
})
</script>
Here is the partial:
#model EcommerceWebsite.Models.Home.DeliveryAddressModel
<div class="modal fade" id="ValidateAddress">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#using (Html.BeginForm("AddShippingAddressToUser", "Home"))
{
#Html.HiddenFor(x => x.strName)
#Html.HiddenFor(x => x.strAttnTo)
#Html.HiddenFor(x => x.strStreet1)
#Html.HiddenFor(x => x.strStreet2)
#Html.HiddenFor(x => x.strCity)
#Html.HiddenFor(x => x.State.StrStateCode)
#Html.HiddenFor(x => x.State.StrStateName)
#Html.HiddenFor(x => x.State.IntStateId)
#Html.HiddenFor(x => x.strZip)
#Html.HiddenFor(x => x.strPhoneNumber)
#Html.HiddenFor(x => x.blnIsDefault)
<div class="modal-body">
<form action="Create">
<div class="form-group">
#if (Model.ErrorMessage == null)
{
<h5>#Model.strName</h5>
#if (Model.strAttnTo != null)
{<h5>#Model.strAttnTo</h5>}
<h5>#Model.strStreet1</h5>
#if (Model.strStreet2 != null)
{<h5>#Model.strStreet2</h5>}
<h5>#Model.strCity</h5>
<h5>#Model.State.StrStateCode</h5>
<h5>#Model.strZip</h5>
<h5>#Model.strPhoneNumber</h5>
<div class="modal-footer">
<button type="submit" value="Save" class="btn btn-primary">Save</button>
<button type="button" value="Edit" class="btn btn-secondary" data-dismiss="modal">Edit</button>
</div>
}
else
{
<h4>#Model.ErrorMessage</h4>
}
</div>
</form>
</div>
}
</div>
</div>
</div>
When all is said and done and the get validation button is pressed, it's supposed to send all the data to the controller and Verify the address with FedEx. But everything is null..
Now something to note, when I change the return of the httpget to return View(); everything works except it doesn't send the URL.
Update:
The AddShippingAddressToUser() hasn't even been called yet. The error lies somewhere in lines 101 - 102. Inside the button or the line 618 on the home controller.
Update: Here's the Model
public class DeliveryAddressModel
{
//[Required]
//[Display(Name = "First & Last Name")]
public string strName { get; set; }
//[Display(Name = "Attention To")]
public string strAttnTo { get; set; }
//[Required]
//[Display(Name = "Street 1")]
public string strStreet1 { get; set; }
//[Display(Name = "Street 2")]
public string strStreet2 { get; set; }
//[Required]
//[Display(Name = "City")]
public string strCity { get; set; }
//[Required]
//[Display(Name = "State")]
public Tstate State { get; set; }
//[Required]
//[Display(Name = "Zipcode")]
public string strZip { get; set; }
//[Required(ErrorMessage = "You must provide a phone number")]
//[Display(Name = "Phone Number")]
//[DataType(DataType.PhoneNumber)]
//[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string strPhoneNumber { get; set; }
public bool blnIsDefault { get; set; }
public string ErrorMessage { get; set; }
public string strReturnAddress { get; set; }
}
First thing, since your form's function isnt a retrieval operation and a creational operation, use the http verb POST and not GET. Replace the HttpVerb filter above your action from HttpGet to HttpPost.
Second add this:
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Post))
Alternatively,
#using (Html.BeginForm("AddShippingAddressToUser", "Home", FormMethod.Get))
Before your model in the action add: [FromQuery]

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.

C# asp.net issue on Form with file type and text

I'm going straight to the point here guys,
I have a form. when I save the form... it only gets the firstname, middlename and lastname.. it doesn't get the files... however, if I only get the photo and comment out other inputs... the photo is captured on my model.. I dunno why it behaves like this.. I'm really new to asp.net mvc.. so please bear with me..
#model Impulse.ViewModels.AgentViewModel
#{
ViewBag.Title = "AgentForm";
Layout = "~/Views/Shared/_SiteLayout.cshtml";
}
<div class="custom-container">
<h1 class="title"><strong>Add New Agent</strong></h1>
<hr />
#using (Html.BeginForm("Save", "Agent", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<div class="col-md-3">
<div id="preview">
<img src="~/Content/Assets/no-image.png" id="profile_image" class="img-thumbnail" />
</div>
<div class="form-group">
<label>Profile Picture</label>
<input type="file" name="photo" id="photo" />
</div>
</div>
<div class="col-md-9">
<div class="row">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.Agent.FirstName)
#Html.TextBoxFor(m => m.Agent.FirstName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Agent.FirstName)
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.Agent.MiddleName)
#Html.TextBoxFor(m => m.Agent.MiddleName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Agent.MiddleName)
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.Agent.LastName)
#Html.TextBoxFor(m => m.Agent.LastName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Agent.LastName)
</div>
</div>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Save" />
}
</div>
Controller
[HttpPost]
public ActionResult Save(AgentModel agent)
{
//I debug here to see the data passed by my view
return Content("Sample");
}
Model
public class AgentModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
[FileSize(10240)]
[FileTypes("jpg,jpeg,png")]
public HttpPostedFileBase photo { get; set; }
}
you can try like this
Model
public class UploadFileModel
{
public UploadFileModel()
{
Files = new List<HttpPostedFileBase>();
}
public List<HttpPostedFileBase> Files { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
View
#using (Html.BeginForm("UploadData", "Home", FormMethod.Post, new { encType="multipart/form-data" }))
{
#Html.TextBoxFor(m => m.FirstName)
<br /><br />
#Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })<br /><br />
<input type="submit" value="submit" name="submit" id="submit" />
}
Controller
public ActionResult UploadData(UploadFileModel model)
{
var file = model.Files[0];
return View(model);
}
you are binding to view to AgentViewModel so you will get AgentViewModel when you post server. so the parameter to action save should be viewmodel. Or Else change view to bind to AgentModel.
The file control that you have used is html input type. try using below code.
#Html.TextBoxFor(m => Model.File, new { type = "file" , accept=".pdf"})
#Html.ValidationMessageFor(m => Model.File)

NullReferenceException ASP.NET MVC 5

I have a web application with this controller:
public class ServiceRequestController : Controller
{
[Authorize(Roles = "Customer")]
public ActionResult Create()
{
return View();
}
[Authorize(Roles = "Customer")]
public ActionResult CreateNewUserAccount()
{
return View();
}
[Authorize(Roles = "Customer")]
[HttpPost]
public ActionResult CreateNewUserAccount(ServiceRequest serviceRequest)
{
if (ModelState.IsValid)
{
serviceRequest.Log.Id = User.Identity.GetUserId().ToString();
serviceRequest.Log.DateTimeLogged = System.DateTime.Now;
serviceRequest.LogID = db.Logs.Max(item => item.LogID);
serviceRequest.EstimatedResolveDate serviceRequest.CalculateEstimatedResolveDate();
db.ServiceRequests.Add(serviceRequest);
db.SaveChanges();
return RedirectToAction("AllServiceRequests", "Log");
}
return View(serviceRequest);
}
The serviceRequest.Log.Id = User.Identity.GetUserId().ToString(); (And any preceding line if this is commented out) throws a null reference exception. I presume the serviceRequest is somehow null?
The ActionLink which requests the CreateNewUserAccount() page is:
#Html.ActionLink("New User Account", "CreateNewUserAccount", "ServiceRequest")
I'm not sure how to resolve this exception?
The model is:
public partial class ServiceRequest
{
public int ServiceRequestID { get; set; }
public Nullable<int> LogID { get; set; }
public string RequestType { get; set; }
[DisplayName("Additional Information")]
[Required]
[StringLength(200)]
public string AdditionalInformation { get; set; }
public DateTime EstimatedResolveDate { get; set; }
[Required]
[DisplayName("Delivery Date")]
public DateTime DeliveryDate { get; set; }
public virtual Log Log { get; set; }
public DateTime CalculateEstimatedResolveDate()
{
return System.DateTime.Now.AddDays(3);
}
}
View code:
#model OfficiumWebApp.Models.ServiceRequest
#{
ViewBag.Title = "New User Account";
}
#using(Html.BeginForm("CreateNewUserAccount", "ServiceRequest", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.RequestType, new { #class = "control-label col-md-2" })
<div class="col-md-3">
<div class="editor-field">
#Html.TextBoxFor(model => model.RequestType, new { #Value = ViewBag.Title, #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.RequestType)
</div>
</div>
</div>
<div class="form-group">
#Html.Label("Name of Account Holder", new { #class = "control-label col-md-2" })
<div class="col-md-3">
<div class="editor-field">
#Html.TextBox("AccountName")
#Html.ValidationMessageFor(model => model.RequestType)
</div>
</div>
</div>
<div class="form-group">
#Html.Label("Department", new { #class = "control-label col-md-2" })
<div class="col-md-3">
<div class="editor-field">
#Html.TextBox("Department")
#Html.ValidationMessageFor(model => model.RequestType)
</div>
</div>
</div>
<div class="form-group">
#Html.Label("Location", new { #class = "control-label col-md-2" })
<div class="col-md-3">
<div class="editor-field">
#Html.TextBox("Location", null, new { id = "Location" }))
#Html.ValidationMessageFor(model => model.RequestType)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdditionalInformation, new { #class = "control-label col-md-2" })
<div class="tags">
<div class="col-md-10">
#Html.TextAreaFor(model => model.AdditionalInformation)
#Html.ValidationMessageFor(model => model.AdditionalInformation)
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DeliveryDate, new { #id = "VisitDateLabel", #class = "control-label col-md-2" })
<div class="col-md-3">
<div class="editor-field">
#Html.JQueryUI().DatepickerFor(model => model.DeliveryDate).Inline(false)
#Html.ValidationMessageFor(model => model.DeliveryDate)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
</div>
</div>
</div>
}
You need to return the view i.e.
[Authorize(Roles = "Customer")]
public ActionResult CreateNewUserAccount()
{
var model = new ServiceRequest();
model.Log = new Log();
return View(model);
}
In your view you need to add a model reference too at the top i.e.
#model ServiceRequest
You could also initialise the Log object in your model as follows:
public class ServiceRequest
{
public ServiceRequest()
{
Log = new Log();
}
....
}
An action link will not post your model back, you need to include it within a form and include all the model values that you want to be updated on the client i.e.
#using (Html.BeginForm("CreateNewUserAccount", "ServiceRequest", FormMethod.Post)){
#Html.EditorFor(m => m.AdditionalInformation)
...
<input type="submit" value="submit" />
Update
Taken from the below comments, this was resolved by creating a new log on post i.e.
var log = new Log {
Id = User.Identity.GetUserId().ToString(),
DateTimeLogged = System.DateTime.Now,
LogID = db.Logs.Max(item => item.LogID) };
serviceRequest.Log = log;

Categories