MVC submit isn't returning all data - c#

I'm writing an MVC app which ends up accessing a SQL database. On my edit page, I previously had every item available to be edited that is in the model. Recently I was asked to no longer allow the user to edit the primary keys. I did a quick change to change the primary key fields (in this example, there are 2 of them) from an EditorFor to a DisplayFor. The new view is this:
#model App.Data.Item
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Item</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
<strong>ID:</strong>
<div class="col-md-10">
<p>#Html.DisplayFor(model => model.ID)</p>
</div>
</div>
<div class="form-group">
<strong>ID2:</strong>
<div class="col-md-10">
<p>#Html.DisplayFor(model => model.ID2)</p>
</div>
</div>
<div class="form-group">
<strong>Description:</strong>
<div class="col-md-10">
<p>#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)</p>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary">Submit <i class="fa fa-caret-right"></i></button>
</div>
</div>
</div>
}
It used to work with the full editing. Now the data is displayed properly, as expected. However, when submit is pressed, Null values are passed back to the controller for the values that are displayed.
These are the edit functions in my controller. ItemService.Edit() just saves the data to the server. It works correctly.
[Authorize]
public ActionResult Edit(string id)
{
if (id == null)
{
//return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string[] vals = id.Split('|');
ItemAttribute itemAttribute = itemAttributeService.Find(int.Parse(vals[0]), vals[1]);
if (itemAttribute == null)
{
return HttpNotFound();
}
return View(itemAttribute);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult Edit([Bind(Include = "ID,ID2,Description")]
Item item)
{
if (item.Description == null)
{
ModelState.AddModelError("Description", "Description cannot be null.");
}
if (ModelState.IsValid)
{
itemService.Edit(item);
return RedirectToAction("../Home/Index/");
}
return View(item);
}
Lastly, my data model:
public class Item
{
public int ID { get; set; }
public string ID2 { get; set; }
public string Description { get; set; }
}
Why is the data no longer being passed back to the second function, and how do I get it to pass correctly so that I can save it to the database?

You need to have an input element generated for the items that you want returned. Currently, you are only displaying two of your model elements and have no associated input with them. As a result, they will not be POSTed back to the server.
To get them to post to the server and not "editable" from a textbox, add a Html.HiddenFor() helper for each of the items that you need returned.
<div class="form-group">
<strong>ID:</strong>
<div class="col-md-10">
<p>#Html.DisplayFor(model => model.ID)</p>
<p>#Html.HiddenFor(model => model.ID)</p>
</div>
</div>
<div class="form-group">
<strong>ID2:</strong>
<div class="col-md-10">
<p>#Html.DisplayFor(model => model.ID2)</p>
<p>#Html.HiddenFor(model => model.ID)</p>
</div>
</div>
However, keep in mind that anyone can edit the HTML using Firebug or Chrome console tools and submit any value that they want for any field, even if you did not want to change it. Be sure that when you are persisting the changes to the database, you are NOT including these fields as part of the update.

Try this, just before this line of code:
#Html.DisplayFor(model => model.ID)
put in this for debugging:
#Html.LabelFor(model => model.ID)
Tell us what you see...
If you see the label then check your controller, in particular the parameter it takes on the post. It should take and Item of type ITEM per your model.
Before the controller receives the data MVC has to try to populate the data... It converts name/value pairs to model types with values secretly. If you don't see any data after you are in the controller it's usually because the names were not found!

Related

Blank form appears after submitting in ASP.NET Core?

I have an application that has multiple tabs to submit a form. However, users are getting a blank form after hitting submit, and are not redirected to the confirmation page. This is odd because some applications are submitting fine, while others are not storing the data from fields to the database. My first guess was that it was a firewall issue. I am using a post method for submit. Another note, this is something that is occurring on our production server but not on our local development environment.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Applicant")]
public IActionResult Application(ApplicationViewModel model)
{
var saved = false;
model = _applicantManager.RebuildApplicationViewModel(model);
if (ModelState.IsValid)
{
saved = _applicantManager.SubmitApplication(model, CurrentUser.UserName);
return RedirectToAction("Index");
}
return View(model);
}
Form (Rather large so shortened for simplicity):
#Html.ValidationSummary(excludePropertyErrors: false, message: "", htmlAttributes: new { #style = "color:red" })
<ul class="wdn_tabs">
<li>Personal</li>
<li>Academic</li>
<li>Questions</li>
<li>Availability & Reference</li>
</ul>
#using (Html.BeginForm(actionName: "Application", controllerName: "Applicant", method: FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="wdn_tabs_content">
<div id="personalTab">
<h4>Personal Information</h4>
<div style="color:red"><strong>All fields are required.</strong></div>
<div class="tabBody">
<div class="inputGroup spacer">
<strong>#Html.DisplayNameFor(x => x.PersonalInfo.FirstName)</strong>
#Html.ValidationMessageFor(x => x.PersonalInfo.FirstName)
#Html.TextBoxFor(x => x.PersonalInfo.FirstName)
</div>
<div class="inputGroup spacer">
<strong>#Html.DisplayNameFor(x => x.PersonalInfo.LastName)</strong>
#Html.ValidationMessageFor(x => x.PersonalInfo.LastName)
<input type="text" asp-for="PersonalInfo.LastName" />
</div>
..........................other fields..........................
</div>
<div class="tabFooter">
Back
<button type="submit" class="wdn-button wdn-button-complement">Submit</button>
</div>
</div>
</div>
}

c# mvc form: how to build view for simple feedback form leveraging the benefit of using html.editorfor?

I have simple input form (basically for feedback) with following fields:
Name, Gender, Mobile-Number, Complaint text. (To simplify I am not mentioning any POST action OR submit button on the form)
Currently, I have created following MVC structure:
public class ComplaintController
{
[HttpGet]
public ActionResult Index()
{
return View(); //This view displays the complaint form with all above fields
}
}
I read this and several other links where they suggest to use #Html.EditorFor as it creates UI based on model data-type.
Currently, I am not passing any model to the [HttpGet] view. If I want to use #Html.EditorFor, I need to pass my model to [HttpGet] Index View, how can I do that? What is best pratise to create such MVC forms?
Your Controller:
public ActionResult Index()
{
whateverModel d = new whateverModel();
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(whateverModel m)
{
if (ModelState.IsValid)
{
//its valid, update your database or do soemthing useful here
return RedirectToAction("Success");
}
//its not valid reload the page and let data annotations show the error
return View(m);
}
Once you have your code in the controller then you can have visual studio auto-create your view. In your controller, right click the "d" in return View(d); and select "Add View." Change the Template to "create" and Model class to your Model (whateverModel in this example). It will auto generate the chtml page for you with the model imported and the editors already generated for you. Example auto generated view below. The you can work on styling and such.
cshtml:
#model YourSolution.Models.whateverModel
#{
ViewBag.Title = "Whatever";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Whatever</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Whatever</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FriendlyName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FriendlyName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FriendlyName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Order, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Order, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Order, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Currently, I am not passing any model to the [HttpGet] view. If I want
to use #Html.EditorFor, I need to pass my model to [HttpGet] Index
View, how can I do that?
Hi sahil ,As a first step , create one model class like below
public class FeedBack
{
public string Name{get;set;}
public string Gender{get;set;}
public int Mobile-Number{get;set;}
public string Complaint{get;set;}
// other additional fields
}
And in the controller get method ,pass a model like below
public class ComplaintController
{
[HttpGet]
public ActionResult Index()
{
FeedBack OBJFeedback = new FeedBack();
return View(OBJFeedback);
}
}
And in a view , strongly type this model and post the data as you want to the controller post methods.
Here is the example of strongly typed view : http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/
Important Note : In the get action method , since you dont want to display any values by default in the view , even if you dont pass model object it will work in the same way.
Hope the above information was useful
Thanks
Karthik
If you want to use #Html.EditorFor, then you mast pass the model to the view.What does #Html.EditorFor do? It makes the html tag like
<input class="text-box single-line" id="Name" name="Name" type="text" value="">
So if you do not want to pass the model to the view then you need to write the raw html tag like above. It is important to keep the html tag's name property same as the mvc's model property because when you want to post the data to the controller the name property of the html tag will map the mvc model property and get the corresponding value at the Controller method.
At the view(somthing.cshtml) you can use html tags, because .cshtml==.cs+html . So the whole code look like
Controller methods
public ActionResult FeedBack()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FeedBack(FeedBackModel Model)
{
var feedBack = Model;
return View();
}
And the View
<form action="/Home/FeedBack" method="post" id="feedBackForm">
#Html.AntiForgeryToken()
<hr>
<div class="form-group">
<div class="col-md-5">
<label for="Name">Name</label>
</div>
<div class="col-md-5">
<input class="text-box single-line" name="Name" type="text">
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="Name">Gender</label>
</div>
<div class="col-md-5">
<select name="Gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="Name">MobileNumber</label>
</div>
<div class="col-md-5">
<input class="text-box single-line" name="MobileNumber" type="text">
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="Name">Complaint</label>
</div>
<div class="col-md-5">
<textarea class="text-box single-line" name="Complaint"></textarea>
</div>
</div>
<div class="col-md-5">
<input type="submit" value="Create" class="btn btn-default">
</div>
</form>
If you do not want to use submit then you can use ajax.

MVC 5 Viewmodel binding works but post back is partial filled

I have a parameterless Index for the HttpGet which works. But when I post it the HttpPost version of Index is invoked and the viewmodel object is passed in, but there is only the value of the dropdown in it. The rest is null (products, title)
[HttpPost]
public ActionResult Index(ProductsViewModel pvm)
{
// breakpoint on line 36, shows that pvm.Title is null and Products too.
return View(pvm);
}
My compilable and running example can be downloaded from my OneDrive http://1drv.ms/1zSsMkr
My view:
#model KleinKloteProductOverzicht.Models.ProductsViewModel
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect"})
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#foreach (var item in Model.Products)
{
#Html.DisplayFor(i => item.Name);
}
</div>
}
}
If I have this view model:
public class ViewModel
{
public string Name {get;set;}
public string SelectedLocation {get;set;}
public IEnumerable<SelectListItem> Locations {get;set;}
}
And your actions look like this:
public ActionResult MyForm()
{
var vm = new ViewModel
{
Locations = context.Locations.ToList() // Some database call
}
return View(vm);
}
[HttpPost]
public ActionResult MyForm(ViewModel vm)
{
vm.Locations // this is null
}
It is null because the model binder can't find a form control that is setting its data.
The <form> must set some data in the view for the model binder to pick it up.
<form>
Name: <input type="text" id="name" />
</form>
This will set the Name property on the view model, because the model bind can see the id of the form control and uses that to know what to bind to.
So in terms of your view, you need to make sure you wrap any content that you want to post back to the server with #using(Html.BeginForm())
Anyway this is my guess.
Well, you seem to be confused as to how [HttpPost] and form tags interact with eachother.
You see, when .NET MVC binds your parameters in your controller actions, it tries to derive that data from the request. For [HttpGet] it does this by looking at the query string.
For [HttpPost] calls, it also looks at the Request.Form. This variable is populated with the values of all input fields that were inside the form you submitted.
Now, this is your view:
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect" })
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#foreach (var item in Model.Products)
{
#Html.DisplayFor(i => item.Name);
}
</div>
}
}
You only have one select tag (generated by Dropdownlistfor) but no other inputs. That's why .NET MVC cannot infer any other data for your view model.
If you change your view to this:
#model KleinKloteProductOverzicht.Models.ProductsViewModel
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect" })
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#for (var i = 0; i < Model.Products.Count; i++)
{
#Html.DisplayFor(model => model.Products[i].Name)
#Html.HiddenFor(model => model.Products[i].ID)
}
</div>
}
}
You'll see I've added a hidden input (<input type="hidden">) for the product id. Note that the product name still will be null.
I would suggest you follow a tutorial on .NET MVC and read up on some of the concepts behind it, because the very fact that you ask this question reveals that you have much to learn.
Best of luck!
P.S. One last tip: #Html.Blablabla writes directly to your view. You usually don't need that ";" at the end, because it will be inside your generated html.
Your property is not associated with a "postable" control, therefore it will not be submitted along with the form data. If your really want to get the value in your Title property, just set it as a hidden input.
#Html.HiddenFor(m => m.Title)
A label will not be posted when submitting a form but an input will. This is exactly what HiddenFor does; it creates a hidden input element which will be picked up by the form submit.

Why does DbContext.Entry(IEnumerable<MedicalProduct>).State produce an ArguementNullException in my code?

In my MedicalProductController, I am trying to make my Edit action able to edit multiple objects on one page. To do that, I plan on my HTTPPOST edit action method receiving an IEnumerable<MedicalProduct> instead of the MedicalProduct that the scaffolding set up for me.
When I click save to submit some changes, I get an ArguementNullException unhandled on the line: _db.Entry(productList).State = EntityState.Modified; and I don't understand why it is null.
MedicalProductController:
public class MedicalProductController : Controller
{
private MvcMedicalStoreDb _db = new MvcMedicalStoreDb();
// some code omitted for brevity
public ActionResult Edit(int id = 0)
{
MedicalProduct product = _db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
var productList = new List<MedicalProduct> { product };
var viewModel = GetMedicalProductViewModelList(productList);
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(IEnumerable<MedicalProduct> productList)
{
if (ModelState.IsValid)
{
_db.Entry(productList).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
//var productList = new List<MedicalProduct> { product };
var viewModel = GetMedicalProductViewModelList(productList);
return View(viewModel);
}
}
Edit.cshtml:
#model IEnumerable<MvcMedicalStore.Models.MedicalProductViewModel>
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>MedicalProduct</legend>
#foreach (var modelItem in Model)
{
#Html.HiddenFor(item => modelItem.ID)
<div class="editor-label">
#Html.LabelFor(item => modelItem.Name)
</div>
<div class="editor-field">
#Html.EditorFor(item => modelItem.Name)
#Html.ValidationMessageFor(item => modelItem.Name)
</div>
<div class="editor-label">
#Html.LabelFor(item => modelItem.Price)
</div>
<div class="editor-field">
#Html.EditorFor(item => modelItem.Price)
#Html.ValidationMessageFor(item => modelItem.Price)
</div>
<div class="editor-label">
#Html.LabelFor(item => modelItem.BrandName)
</div>
<div class="editor-field">
#Html.DropDownListFor(item => modelItem.BrandName, modelItem.BrandSelectListItem)
#Html.ValidationMessageFor(item => modelItem.BrandName)
</div>
}
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
It looks to me like the model binder isn't able to bind to your collection, which would cause it to be null. The reason it's doing that is because you're not specifying an index for each of the elements. That means MVC has no way to determine how to bind them correctly.
Edit
I've figured out why the last revision of this answer didn't work. Firstly, IEnumerable<T> doesn't have a direct indexer. Instead you would use Model.ElementAt(i).ID to access the ID property. However, this actually wouldn't solve the problem with the model binding issue as, for some reason, this doesn't generate the proper indices on the name attributes for the generated <input> fields. (More on this below.)
There are two ways to fix that. The first way would be to pass a List to the view, instead of IEnumerable, then accessing the fields as I showed earlier. However, the better way would be to create an EditorTemplate instead. This will be easier because it saves you having to change your existing methods which are generating your view model. So you'll need to follow these steps:
Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
Create a strongly-typed view in that directory with the name that matches your model (e.g in this case the view would be called MedicalProductViewModel).
Move the bulk of your original view into that new template.
You'll end up with the following:
#model MedicalProductViewModel
#Html.HiddenFor(item => Model.ID)
<div class="editor-label">
#Html.LabelFor(item => Model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(item => Model.Name)
#Html.ValidationMessageFor(item => Model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(item => Model.Price)
</div>
<div class="editor-field">
#Html.EditorFor(item => Model.Price)
#Html.ValidationMessageFor(item => Model.Price)
</div>
<div class="editor-label">
#Html.LabelFor(item => Model.BrandName)
</div>
<div class="editor-field">
#Html.DropDownListFor(item => Model.BrandName, Model.BrandSelectListItem)
#Html.ValidationMessageFor(item => Model.BrandName)
</div>
Notice how we're no longer using any indexing notation to access the model properties.
Now in your Edit.cshtml view, you'd be left with this:
#model IEnumerable<MvcMedicalStore.Models.MedicalProductViewModel>
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>MedicalProduct</legend>
#Html.EditorFor(m => m)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Although I gave a brief explanation at the start, I should really explain what this is actually doing. Your original HTML would have produced output like the following:
<input name="ID" type="text" value="1" />
<input name="Name" type="text" value="Name 1" />
<input name="ID" type="text" value="2" />
<input name="Name" type="text" value="Name 2" />
As you can see, multiple input fields share the same name. That's why the model binder is tripping up, because your action is telling it to bind to a collection and the binder needs to be able to distinguish between each element in the collection. EditorTemplates are smart enough to figure out when you're working with a collection and will apply indices to your input fields automatically. What the code above will do is generate output like this instead:
<input name="[0].ID" type="text" value="1" />
<input name="[0].Name" type="text" value="Name 1" />
<input name="[1].ID" type="text" value="2" />
<input name="[1].Name" type="text" value="Name 2" />
As you can see, the fields now have an index associated with them. That gives the model binder all the information it needs to be able to add all of the items to the collection. Now that's out of the way, we can get back to fixing your product saving code.
What Gert said is still right about the way you're trying to save productList. You need to be setting the EntityState.Modified flag on each individual item in that collection:
if (ModelState.IsValid)
{
foreach (var product in productList)
_db.Entry(product).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
See if that works.

MVC3 Passing Model to Controller - Receiving Null values

I just started working with MVC3 a few weeks ago and being young in the programming ladder I'm still learning quite a bit. I've recently been working with Models, using TextBoxFor and other helpers to populate properties for my "Character" Model.
Essentially what I'm trying to do is define a model and then pass it to my controller, however any property that I have defined as a static value in my Model is being passed as a null value on runtime.
Below are some snippets of the parts needed to understand whats going on..
Character.cs - Model
// Instances of manipulated objects.
otReal db = new otReal();
public player newPlayer = new player();
public byte[] conditions
{
get
{
return newPlayer.conditions;
}
set
{
byte[] array1 = null;
array1 = new byte[16 * 12 * 3];
newPlayer.conditions = array1;
}
}
CharacterController.cs
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Submit(Character c)
{
// Add a new character to the database via LINQ to Entities.
otReal.AddToplayers(c.newPlayer);
otReal.players.AddObject(c.newPlayer);
otReal.SaveChanges();
return View();
}
The only helpers I have in my View are the ones that the user actually needs to interact with. If I go into my controller and set the values there they will get set to the correct value and it will insert. Any help would be greatly appreciated!
Index.cshtml - View
#using (Ajax.BeginForm("Submit", new AjaxOptions { OnComplete = "done" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>New Character Information</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name, "Character Name")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TownList)
</div>
<div class="editor-field">
#* #Html.DropDownList("TownList", ViewData["TownList"] as SelectList)*#
#Html.DropDownListFor(model => model.TownList, ViewData["TownList"] as SelectList)
#Html.ValidationMessageFor(model => model.TownList)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Sex)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Sex, ViewData["sex"] as SelectList)
#Html.ValidationMessageFor(model => model.Sex)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Vocation)
</div>
<div class="editor-field">
#Html.DropDownList("VocList", ViewData["VocList"] as SelectList)
#Html.ValidationMessageFor(model => model.Vocation)
</div>
<p>
<input id="button" type="submit" value="Create" />
</p>
<div style="font-family: Tahoma; font-size: large" id="completeDiv" style="display: none;">
</div>
<span></span>
</fieldset>
}
Basically what I'm trying to do here is create my model that has a bunch of base values that every 'Character' will have in the database table. This way when a player creates his/her character he/she will be able to enter a Character Name, Sex, Class(Vocation), Starting Town and all the other values will be populated behind the scenes and passed to the controller for creation.
Assuming you're trying to set values on 'newPlayer', then you can replace this
public player newPlayer = new player();
with this
public player newPlayer { get; set; }
The default model binder will create everything from the form on post-back--there's no need to instantiate it in the model.
Created a constructor for my model and inside the constructor I set the default values via the newly instantiated player model. Temp fix until I read into ataddeini's solution. Thanks everyone!

Categories