I'm developing a project in MVC 3 (CRUD)... I want to create a reservation for a tennis court...
Page:
So, when I type a "Start time" ("heure de début" in French) I want to increase the "FinishTime" in red ("heure de fin" in French) dynamically... If it's a simple match increase by 1:00 and if not by 2:00...
I'm beginner in MvC3 so I have no idea how to do that... Of course, I'm not request that you make my work but the right method to do that and if it's possible an example...
View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Reservation</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Date)
#Html.ValidationMessageFor(model => model.Date)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StartTime)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartTime)
#Html.ValidationMessageFor(model => model.StartTime)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Simple)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Simple)
#Html.ValidationMessageFor(model => model.Simple)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FinishTime)
</div>
<div class="editor-fieldFinishTime">
#Html.DisplayFor(model => model.FinishTime)
#Html.ValidationMessageFor(model => model.FinishTime)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Customer.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Customer.Name)
#Html.ValidationMessageFor(model => model.Customer.Name)
</div>
<div class="editor-label">
#Html.Label("Terrain N°")
</div>
<div class="editor-field">
#Html.DropDownListFor(c=>c.TennisCourtID,ViewBag.TennisCourtID as SelectList)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I've forget to precise that all clubs can have different schedule... For example:
Club 1:
Simple: 1:00
Double: 2:00
Club2:
Simple: 1:30
Double: 2:30
So in my database's table TennisClub I have an attribute SimpleGameTime and DoubleGameTime... Sorry :(
Bind to the change event of the Input for Start time (check its ID in rendered HTML):
$("input#TheId").bind("onchange", onStartTimeChanged);
Define a function to parse a time, see this post here on SO.
In the onStartTimeChanged function get the check box state (update with correct jQuery selector for the control):
var checked = $('input[type=checkbox]').is(':checked');
Then simply add the parsed date with the proper offset and write that back to the End Time control using toLocaleTimeString().
Note: I assumed you'll use JavaScript to perform calculations on client-side. If you prefer to do everything on server-side you have to add an AJAX-enabled method in your controller with the start time and the flag as parameters. In your onStartTimeChanged function you have to call it and asynchronously update the end time when the function return. If there's a lot of logic (or it's not trivial) I prefer the server-side solution with AJAX.
For example (I didn't check the code so use it cum grano salis) to call a server-side method with POST (you have to pass parameters, as alternative you may use getJson with GET only but you have to work with routing):
function ComputeEndTime(matchStartTime, isSimpleMatch) {
var url = '<%= Url.Action("ControllerName", "ComputeEndTime") %>';
$.post(url, { startTime: matchStartTime, isSimple: isSimpleMatch },
function(data) {
return data.endTime;
}
);
}
And your server side function:
[AcceptPost]
public ActionResult ComputeEndTime(string startTime, bool isSimple)
{
// Perform your calculations then convert to string
string calculatedEndTime = "";
return Json(new { endTime = calculatedEndTime });
}
Related
Have been trying to get a member profile management area working with ajax as each section of the page is hidden within a show hide div.
I have used ajax before in MVC applications but have never used it with umbraco surface controllers before. I'm unsure why returning a partial view in the controller is outputting the whole page and not just the partial view that I am giving to it.
Controller:
[HttpPost]
[ActionName("MvcMemberEditProfileDetails")]
public ActionResult MvcMemberEditProfileDetails(MvcMemberEditProfileDetailsModel model)
{
var memberService = Services.MemberService;
var currentUser = Membership.GetUser();
var member = memberService.GetByEmail(currentUser.Email);
bool result = false;
if (ModelState.IsValid)
{
...
}
if (result)
{
...
}
return PartialView("MvcMemberEditProfileDetails", model);
}
View:
#model Umbraco714.Models.MvcMemberEditProfileDetailsModel
#using (Ajax.BeginForm("MvcMemberEditProfileDetails", "MvcMember", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MvcMemberEditProfileDetails", InsertionMode = InsertionMode.Replace }))
{
if (Model.Result != null)
{
if (Model.Result == true)
{
<div id="result" class="alert alert-success">
#Html.Raw(Model.ResultMessage)
</div>
}
else
{
<div id="result" class="alert alert-danger">
#Html.Raw(Model.ResultMessage)
</div>
}
}
<div class="form-default">
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.LastName)
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.CompanyName)
#Html.TextBoxFor(m => m.CompanyName)
#Html.ValidationMessageFor(m => m.CompanyName)
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(m => m.CompanyPosition)
#Html.TextBoxFor(m => m.CompanyPosition)
#Html.ValidationMessageFor(m => m.CompanyPosition)
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
#Html.LabelFor(m => m.CompanyBio)
<span class="bs-tooltip" data-toggle="tooltip" data-placement="top" title="Max 1000 characters long"><i class="fa fa-info-circle" aria-hidden="true"></i></span>
#Html.TextAreaFor(m => m.CompanyBio, new { #rows = "4", #maxlength = "1000" })
#Html.ValidationMessageFor(m => m.CompanyBio)
</div>
#TempData["Status"]
<div class="form-group nomargin">
<div class="text-right">
<button class="button" type="submit"><i class="fa fa-floppy-o" aria-hidden="true"></i> Update</button>
</div>
</div>
</div>
</div>
</div>
}
I have everything that needs to be included (as far as I'm aware) well before the form and there are no console errors.
<script src="/scripts/jquery.js"></script>
<script src="/scripts/bootstrap.min.js"></script>
<script src="/scripts/jquery-val.js"></script>
<script src="/scripts/jquery.unobtrusive-ajax.min.js"></script>
I have also made sure that UnobtrusiveJavaScriptEnabled is set to true in the web.config but I'm still getting a full page rendered when I post the form.
Initially:
When the page loads and the form shows
After:
When the form is submitted and the correct partial view is returned but inside of an entire
Feeling pretty dumbfounded that I've spent more that a couple of hours looking into this even though it's clearly working in a sort of way.
Is it possible / a known thing for this to happen? I searched around but couldn't find any topics with a similar issue, unless I was just wording things wrong.
Just looking for a nudge in the right direction if anybody has any ideas?
Umbraco can be funny with partials. Try returning CurrentUmbracoPage() in the controller.
As for the message, you could use TempData as it only lasts for one request, rather than the model.
I have an Edit view which displays some of my fields as follows:
<table>
<tr>
<td style="width:40%; vertical-align:top">
<div class="editor-label">
#Html.LabelFor(model => model.CREATED_DATE)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.CREATED_DATE)
#Html.ValidationMessageFor(model => model.CREATED_DATE)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LAST_MODIFIED_DATE)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.LAST_MODIFIED_DATE)
#Html.ValidationMessageFor(model => model.LAST_MODIFIED_DATE)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.STATUS)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.STATUS, Model.Statuses)
#Html.ValidationMessageFor(model => model.STATUS)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SEVERITY)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SEVERITY, Model.Severities)
#Html.ValidationMessageFor(model => model.SEVERITY)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRIORITY)
</div>
<div id="priorityDiv" class="editor-field">
#Html.EditorFor(model => model.PRIORITY)
#Html.ValidationMessageFor(model => model.PRIORITY)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DESCRIPTION)
</div>
<div id="descriptionDiv" class="editor-field">
#Html.EditorFor(model => model.DESCRIPTION)
#Html.ValidationMessageFor(model => model.DESCRIPTION)
</div>
</td>
</tr>
</table>
In essence I want users to be able to edit any field except for the two at the top, CREATED_DATE and LAST_MODIFIED_DATE. However, when I hit the submit button the two date fields come back as null. My controller code is below.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Alert alert)
{
if (ModelState.IsValid)
{
alert.LAST_MODIFIED_DATE = DateTime.Now;
db.Entry(alert).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(alert);
}
Is there a way to prevent the user from editing a field in a View without the content of filed being returned to the controller as null?
Add them to your view in hidden fields inside the form:
<div class="editor-field">
#Html.DisplayFor(model => model.CREATED_DATE)
#Html.HiddenFor(model => model.CREATED_DATE)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.LAST_MODIFIED_DATE)
#Html.HiddenFor(model => model.LAST_MODIFIED_DATE)
</div>
This will make them post back to your Edit method without the user being able to edit them. You can also remove the ValidationMessages for this fields as they cannot be edited and therefore won't need to display validation messages.
EDIT:
As #JLRishe pointed out this would give the users the power to edit the values using their browsers debug tools.
Another solution could be to create a view specific model, and only map the values you want adjusted to your database object. More info about that here: Real example of TryUpdateModel, ASP .NET MVC 3
I am getting a dump ONLY in the server and not in my local system when trying to post the data. There is a page which submits some value to the database. I have also modeled the dropdown in the page as mandatory. However, when clicking on "Create", instead of giving an error like "Missing"; it throws a dump.
Dump trace:
Value cannot be null.
Parameter name: items
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: items
Source Error:
Line 65: </div>
Line 66: <div class="editor-field">
Line 67: #Html.DropDownListFor(x => x.ProjectName, new SelectList(Model.ProjectDetail, "ProjectName", "ProjectName"),"")
Line 68: <span runat="server" style="color:Red;" visible="false"> *</span>
Line 69: #Html.ValidationMessageFor(model => model.ProjectName)
Source File: d:\hosting\11178048\html\fbpm\fbpm\Views\User\Create.cshtml Line: 67
Stack Trace:
[ArgumentNullException: Value cannot be null. Parameter name: items] System.Web.Mvc.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, IEnumerable selectedValues)
+289714 System.Web.Mvc.SelectList..ctor(IEnumerable items, String dataValueField, String dataTextField) +19 ASP._Page_Views_User_Create_cshtml.Execute() in d:\hosting\11178048\html\fbpm\fbpm\Views\User\Create.cshtml:67 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81 System.Web.WebPages.StartPage.RunPage() +17
The Controller code:
public ActionResult Create()
{
var model = new UserDetail
{
ProjectDetail = db1.ProjectDetails.ToList()
};
return View(model);
}
//
// POST: /User/Create
[HttpPost]
public ActionResult Create(UserDetail userdetail)
{
if (ModelState.IsValid)
{
db.UserDetails.Add(userdetail);
db.SaveChanges();
return RedirectToAction("SearchCust");
}
return View(userdetail);
}
The view code:
#model fbpm.Models.UserDetail
#{
ViewBag.Title = "Create Customer";
}
<h2>Create Customer</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Customer Detail</legend>
<div id ="left" style="float:left; width:400px;">
<div class="editor-label">
#Html.LabelFor(model => model.UserID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserID)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.UserID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PANNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PANNo)
#Html.ValidationMessageFor(model => model.PANNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmailID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailID)
#Html.ValidationMessageFor(model => model.EmailID)
</div>
<br />
<p>
<input type="submit" value="Create Customer" />
</p>
</div>
<div id = "left3" style="float:left; width:400px">
<div class="editor-label">
#Html.LabelFor(model => model.ProjectName)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ProjectName, new SelectList(Model.ProjectDetail, "ProjectName", "ProjectName"),"")
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.ProjectName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.BookedDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BookedDate)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.BookedDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.BookedAmount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BookedAmount)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.BookedAmount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Contact1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Contact1)
#Html.ValidationMessageFor(model => model.Contact1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Contact2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Contact2)
#Html.ValidationMessageFor(model => model.Contact2)
</div>
</div>
<div id="left1" style="float:left; width:400px;">
<div class="editor-field">
#Html.HiddenFor(model => model.Role, new { #readonly = "readonly", #Value = "400" })
#Html.ValidationMessageFor(model => model.Role)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FullAddress)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.FullAddress)
#Html.ValidationMessageFor(model => model.FullAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.State)
#Html.ValidationMessageFor(model => model.State)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Country)
#Html.ValidationMessageFor(model => model.Country)
</div>
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "SearchCust")
</div>
I have searched a lot in the net and found that adding a viewbag for the project name in the submit action before returning the view owuld help; but, it didnt. Please can someone help?
Regards
I'm assuming you only see this exception when your insert fails; you then try to reuse the UserDetail model in the view for the same page.
The error you are seeing is due to the nature of working with HTTP - anything that is not directly bound to an input is not retained. So, when you attempt to rebuild the view, the list you are trying to bind the drop-down helper to is null, since UserDetail.ProjectDetail has not been repopulated. You can fix this like so:
[HttpPost]
public ActionResult Create(UserDetail userdetail)
{
if (ModelState.IsValid)
{
db.UserDetails.Add(userdetail);
db.SaveChanges();
return RedirectToAction("SearchCust");
}
userdetail.ProjectDetail = db1.ProjectDetails.ToList();
return View(userdetail);
}
I noticed that create button is a submit button
So it must call action with HttpPost attribute
[HttpPost]
public ActionResult Create(UserDetail userdetail)
In this action, it returns View(userdetail);
But this userdetail object is created by model binder from the submit data from browser.
So it won't have values in ProjectDetail property.
You can step it through
i have added extra three input fields to my view to enable the system admin to submit four objects at the same time instead of one object at a time; the view looks as the following:-
#model Elearning.Models.Answer
#{
ViewBag.Title = "Create";
}
<div id = "partialWrapper">
#using (Ajax.BeginForm("Create", "Answer", new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "incrementanswer",
OnSuccess = "removePartial",
LoadingElementId = "progress2"
}))
{
<div id = "returnedquestion">
#Html.ValidationSummary(true)
<fieldset>
<legend>Answer here</legend>
<ol>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[0].Description")
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div>
</li>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[1].Description")
#Html.ValidationMessageFor(model => model.Description)
</div> <div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div> </li>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[2].Description")
#Html.ValidationMessageFor(model => model.Description)
</div> <div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div> </li>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[3].Description")
#Html.ValidationMessageFor(model => model.Description)
</div> <div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div> </li>
<ol>
</fieldset>
<input type= "hidden" name = "questionid" value = #ViewBag.questionid>
<input type= "hidden" name = "assessmentid" value = #ViewBag.assessmentid>
<input type="submit" value="Add answer" />
</div>
}
</div>
and the following Post Ation Method:-
[HttpPost]
public ActionResult Create(int questionid, ICollection<Answer> answer)
{
if (ModelState.IsValid)
{
foreach (var a in answer){
repository.AddAnswer(a);
repository.Save();
}
return PartialView("_details2",answer);
}
return View("_details2",answer);}
and last thing the _details2 partial view which contains the newly added objects:-
#model IEnumerable<Elearning.Models.Answer>
#{
ViewBag.Title = "Details";
}
#foreach (var m in Model)
{
<tr id = #m.AnswersID>
<td>
#Html.DisplayFor(modelItem => m.Description)
</td>
<td>
#*#Html.DisplayFor(modelItem => Model.Answer_Description.description)*#
#ViewBag.Answerdesription
</td>
<td>
#Ajax.ActionLink("Delete", "Delete", "Answer",
new { id = m.AnswersID },
new AjaxOptions
{
Confirm = "Are You sure You want to delete this Answer ?",
HttpMethod = "Post",
UpdateTargetId = #m.AnswersID.ToString(),
OnSuccess = "removePartial2"
})
</td>
</tr>
}
but the above is not working nethier the objects will be added nor the partial view will be returned , so how i can solve this issue???
BR
You bind your view to a single Elearning.Models.Answer object, how are you expecting to get a collection of Answers as a parameter in your Action? The default model binder will try to bind your view fields to the parameter in the Action but it won't be able to as it's a collection.
What you could try to do is to bind your View to a List<Elearning.Models.Answer> and feed it 4 empty Answer objects, then you can create a strongly typed Partial view that expects one Elearning.Models.Answer, add the Partial in a foreach and, when posting the form, expect that the default model binder does it work and fill your action method with a brand new List of Answer objects.
As an alternative, you can create a View Model object that contains the fields in your View, including those 4 description fields. You add them as Html.TextboxFor to bind each of them to a different property in the View Model. Then you can collect them in your action, provided you change it to public ActionResult Create(int questionid, ViewModelAnswer answer)
Does it make sense?
Your model should contain a list and code like this:
#for (int i=0; i < Model.FavouriteMovies.Count; i++) {
#Html.LabelFor(model => model.YourList[i].Field)
#Html.EditorFor(model => model.YourList[i].Field)
#Html.ValidationMessageFor(model => model.YourList[i].Field)
}
which will print something like:
<label for="YourList_0__Field">Field Name</label>
The Field Name field is required.
And receive the model back in your controller:
public ActionResult MyAction(MyModel model)
{
// First element?
model.YourList[0].
}
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!