Asp.net Cant Post Value to Controller - asp.net

I want to post email and password to Another Controller's action (to Create )
But values are not posted. When i look at the User1Controller's its writing values are Null like in the screenshot. Please help I'm stuck with this hours and cant understand
ScreenShot
My User1.cs
public partial class Users1
{
public string userEmail { get; set; }
public string userPassword { get; set; }
}
My User1Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "userEmail,userPassword")] Users1 baska)
{
if (ModelState.IsValid)
{
db.Users1.Add(baska);
db.SaveChanges();
return RedirectToAction("Index","Home");
}
return RedirectToAction("Login", "Home");
}
My Login.cshtml file
#using (Html.BeginForm("Create","Users1",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="custom-login-panel">
<div class="container">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<img class="profile-img" src="~/images/userlogo.svg"
alt="">
<div class="form-login">
<h4 style="color:white;">Giriş ve Kayıt Ekranı</h4>
<div class="form-group">
#Html.EditorFor(m => m.user1.userEmail, new { htmlAttributes = new { #class = "form-control" ,placeholder="Email" } })
#*#Html.ValidationMessageFor(model => model.user1.userEmail, "", new { #class = "text-danger" })*#
</div>
<div class="form-group">
#Html.EditorFor(m => m.user1.userPassword, new { htmlAttributes = new { #class = "form-control", placeholder = "Passwordd" } })
#*#Html.ValidationMessageFor(model => model.user1.userPassword, "", new { #class = "text-danger" })*#
</div>
<div class="wrapper">
<div class="form-group">
<span class="group-btn">
<input style="width:40%;" type="submit" value="Giriş" class="submit btn btn-primary">
<input style="width:40%;" type="submit" value="Kayıt Ol" class="submit btn btn-primary">
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}

On your Login.cshtml:
you should declare your model.
On your httpget action:
you should declare a new instance of your Users1 class and pass it like a parameter to your return() method.
On your httppost action:
You should receive the model as parameter.
I guess that with these changes, it would work.

Related

how to pass list of object from view to controller in asp.net mvc

first i create list of models in [HttpGet] action and return to view.
public ActionResult Setting()
{
var model = db.Settings.ToList();
return View(model);
}
them in view get list in view and show good.
but after edit the value of setting i want to pass list of object from view to controller don't work this.
#model List<TajerWebsite.Models.Setting>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<!-- left column -->
<div class="col-md-6">
<!-- general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">تنظیمات</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
#using (Html.BeginForm("Setting","Admin", new { FormMethod.Post }))
{
#Html.AntiForgeryToken()
foreach (var item in Model)
{
<div class="card-body">
<div class="form-group">
#Html.HiddenFor(model => item.Id)
<label for="exampleInputPassword1">#item.Name</label>
#Html.EditorFor(model => item.Value, new { htmlAttributes = new { #class = "form-control"} })
#Html.ValidationMessageFor(model => item.Value, "", new { #class = "text-danger" })
</div>
</div>
}
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">ذخیره</button>
</div>
}
</div>
</div>
</div>
</div>
</section>
and action is :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Setting(IEnumerable<Models.Setting> settings)
{
db.Entry(settings);
db.SaveChanges();
return View(settings);
}
but settings is null!
You can't use #foreach loop in the view in order to pass list of object back to the controller, because that would generate input elements with same IDs and Names.
Instead, use standard for loop:
for(int i = 0; i < Model.Count; i++)
{
<div class="card-body">
<div class="form-group">
#Html.HiddenFor(m => m[i].Id)
<label for="exampleInputPassword1">#Model[i].Name</label>
#Html.EditorFor(m => m[i].Value,
new { htmlAttributes = new { #class = "form-control"} })
#Html.ValidationMessageFor(m => m[i].Value,
new { #class = "text-danger" })
</div>
</div>
}

ASP.NET REPLACING Request.IsAuthenticated with a bool is generatig System.NullReferenceException: Object reference not set to an instance of an object

The errors:
Breakpoints and errors
Error from the browser
I want to replace the Request.IsAuthenticated because I have different register and login methods fro the standard template. I wanted to replace with a bool, I have also tried with an int as you will see in the code bellow.
This is my AccountController.cs login method where I'm using the bool Authenticated :
//GET: Account/LoginTurist (new)
[HttpGet]
[AllowAnonymous]
public ActionResult LoginTurist()
{
return View();
}
//POST: Account/LoginTurist (new)
[HttpPost]
[AllowAnonymous]
public ActionResult LoginTurist(LoginVM obj)
{
bool userExists = db.Users.Any(u => u.Username == obj.Username && u.Password == obj.Password);
var viewModel = new LoginVM { Authenticated = Request.IsAuthenticated };
//var viewModel = new LoginVM { Authenticated = 0 };
if (userExists)
{
Session["UseId"] = db.Users.Single(x => x.Username == obj.Username).Id;
viewModel.Authenticated = true;
//viewModel.Authenticated = 1;
return RedirectToAction("Experiences", "Home");
}
// in case of incorect email or password
ViewBag.LoginMessage = "Nume utilizator sau parola incorecte!";
return View(viewModel);
}
This is the model LoginVM:
namespace TuristWithComments.ViewModels
{
public class LoginVM
{
[Required]
[Display(Name = "Nume Utilizator")]
public string Username { get; set; }
[Required, DataType(DataType.Password)]
[Display(Name = "Parola")]
public string Password { get; set; }
[Display(Name = "Recunoaste dispozitivul?")]
public bool RememberMe { get; set; }
public bool Authenticated { get; set; }
//public int Authenticated { get; set; }
}
}
And this is the view, the LoginPartial.cshtml, where I a trying to replace the Request.IsAuthenticated like this:
#*#using Microsoft.AspNet.Identity*#
#*#if (Request.IsAuthenticated)*#
#model TuristWithComments.ViewModels.LoginVM
#if (Model.Authenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", #class = "navbar-right" }))
{
#Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
#*#Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })*#
</li>
<li>Log off</li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
#*<li>#Html.ActionLink("Inregistrare", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>*#
#*<li>#Html.ActionLink("Autentificare", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>*#
<li>#Html.ActionLink("Inregistrare", "RegisterTurist", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>#Html.ActionLink("Autentificare", "LoginTurist", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
I can understand that the Model.Authenticated is null (see the first picture) but where exactly can I fix this? Request.IsAuthenticated is from the beggining as false thats why the program runs at start.
How can I fix the Model to not be null?
Or is there maybe a better, different way of changing the Navbar, would you do it another way?
Later edit:
After searching for more answers online I see a lot of mentions about "Web.config", to witch I have not made any modifications and looks like this:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
Could here be the key? Maybe I need to modify something here?
Later Edit 2, after David's comment:
The LoginPartial view is part of the NavigationBar, witch is in the default Layout (or master Layout if you will) where all the pages render and theoretically is the first thing that opens when you run the project, no?!
Here is the Layout page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<!--Lightbox for popup images-->
<link href="~/Content/lightbox.css" rel="stylesheet" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink(" ", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Acasa", "Index", "Home")</li>
<li>#Html.ActionLink("Recomandarile noastre", "Recommendations", "Home")</li>
<li>#Html.ActionLink("Experientele utilizatorilor", "Experiences", "Home")</li>
<li>#Html.ActionLink("Fii spontan!", "Spontaneous", "Home")</li>
<li>#Html.ActionLink("Contacteaza-ne", "Contact", "Home")</li>
<li>#Html.ActionLink("Despre noi", "About", "Home")</li>
</ul>
#Html.Partial("_LoginPartial") // <-- here it is
</div>
</div>
</div>
<div style="padding: 7px">
<img src="~/Content/Images/_banner7.png" class="img-responsive" />
</div>
<div class="panel panel-body">
<div class="col-md-2">
<!--Partial view for the sidemenu-->
#Html.Partial("_SideMenu")
</div>
<div class="col-md-10">
<div>
#RenderBody()
</div>
</div>
</div>
#*<hr />*#
<div class="container body-content">
<footer>
<p>© #DateTime.Now.Year - TuristWithComments in Banat by Ionut Guruian</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", false)
<!--Lightbox for popup images-->
<script src="~/Scripts/lightbox-2.6.js"></script>
</body>
</html>
Also, the action does have a GET, I have added that aswell in the first code snippet.
And the LoginTurist.cshtml where the user puts his credentials to login is this one here:
#using TuristWithComments.Models
#model TuristWithComments.ViewModels.LoginVM
#*#model LoginViewModel*#
#{
ViewBag.Title = "Autentificare";
}
<h2>#ViewBag.Title.</h2>
<div class="row">
<div class="col-md-8">
<section id="loginForm">
#using (Html.BeginForm("LoginTurist", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Autentificare</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>*#
<h5 class="text-danger" style="padding-left:20%">#ViewBag.LoginMessage</h5>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Autentificare" class="btn btn-success" />
</div>
</div>
<p>
#Html.ActionLink("Inregistrare cont nou", "RegisterTurist")
</p>
}
</section>
</div>
<div class="col-md-4">
<section id="socialLoginForm">
#Html.Partial("_ExternalLoginsListPartial", new ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })
</section>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
This doesn't appear to have anything to do with the Authenticated property. Model is null. Because you didn't provide the view with a model:
return View();
should be:
return View(viewModel);

Persist values between multiple Posts

Hello I am not able to retain values on multiple posts and “Post1” action function in my in my controller always has MyViewModelObj.Field2 as null .I expect it to retain the old value in the 2nd post
How to I make the MyViewModel model class object persist the values ?
Mymodels.cs ( Model)
namespace RetainTest.Models
{
public class MyViewModel
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
}
}
RetainView.cshtml ( View )
#model RetainTest.Models.MyViewModel
#{
ViewBag.Title = "RetainView";
}
<h2>RetainView</h2>
#using (Html.BeginForm("Post1", "Retain", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Field1);
#Html.HiddenFor(model => model.Field2);
#Html.HiddenFor(model => model.Field3);
#Html.HiddenFor(model => model.Field4);
<div class="form-horizontal">
<h4>MyViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Field1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Field1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Field1, "", new { #class = "text-danger" })
</div>
</div>
#{
if ( Model.Field2 == "Val2")
{
<div class="form-group">
#Html.LabelFor(model => model.Field2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Field2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Field2, "", 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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
RetainController.cs ( Controller )
namespace RetainTest.Models
{
public class RetainController : Controller
{
// GET: Retain
public ActionResult Index()
{
MyViewModel MyViewModelObj = new MyViewModel();
MyViewModelObj.Field1 = "Val1";
return View("RetainView", MyViewModelObj);
}
[HttpPost]
public ActionResult Post1(MyViewModel MyViewModelObj)
{
if (string.IsNullOrEmpty(MyViewModelObj.Field2 ))
{
MyViewModelObj.Field2 = "Val2";
}
return View("RetainView", MyViewModelObj);
}
}
}
Try this:
namespace RetainTest.Models
{
public class MyViewModel
{
[Required(ErrorMessage = "Field1 is required")]
public string Field1 { get; set; }
[Required(ErrorMessage = "Field2 is required")]
public string Field2 { get; set; }
public string Field3 { get; set; }
public string Field4 { get; set; }
}
}
#model RetainTest.Models.MyViewModel
#{
ViewBag.Title = "RetainView";
}
<h2>RetainView</h2>
#using (Html.BeginForm("Post1", "Retain", FormMethod.Post, new { id = "form", enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Field1);
#Html.HiddenFor(model => model.Field2);
#Html.HiddenFor(model => model.Field3);
#Html.HiddenFor(model => model.Field4);
<div class="form-horizontal">
<h4>MyViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<Label for="Field1" class="control-label col-md-2">Field1 </label>
<div class="col-md-10">
#if(Model.Field1 == "Val1")
{
<input type="text" name="Field1" id="Field1" class="form-control" value="#Model.Field1">
}
else
{
<input type="text" name="Field1" id="Field1" class="form-control">
}
<span class="field-validation-valid text-danger"
data-valmsg-for="Field1"
data-valmsg-replace="true">
</span>
</div>
</div>
<div class="form-group">
<Label for="Field2" class="control-label col-md-2">Field2 </label>
<div class="col-md-10">
#if(Model.Field2 == "Val2")
{
<input type="text" name="Field2" id="Field2" class="form-control" value="#Model.Field2">
}
else
{
<input type="text" name="Field2" id="Field2" class="form-control">
}
<span class="field-validation-valid text-danger"
data-valmsg-for="Field2"
data-valmsg-replace="true">
</span>
</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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
namespace RetainTest.Models
{
public class RetainController : Controller
{
private MyViewModel MyViewModelObj = new MyViewModel();
// GET
public ActionResult Index()
{
if (Session["MyObj"] != null)
MyViewModelObj = (MyViewModel)Session["MyObj"];
else
MyViewModelObj.Field1 = "Val1";
return View("RetainView", this);
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Post1(FormCollection form)
{
MyViewModelObj.Field1 = form.Get("Field1");
MyViewModelObj.Field2 = form.Get("Field2");
if (string.IsNullOrEmpty(MyViewModelObj.Field2))
MyViewModelObj.Field2 = "Val2";
// here you need to store the data somewhere!
// session, database.
// just an example:
Session.Add("MyObj", MyViewModelObj);
return View("RetainView", this);
}
}
}
I used the session to retain the values of the object but there are a few other ways to store the data. The above code will post the user input to the controller and retain he values in the session.
Got answer from Stephen Muecke
"Your view has a hidden input for each property of your model. The DefaultModelBinder reads the first name/value pair for each property in the request and ignores all others. Since the hidden inputs are first, the values of your EditorFor() methods are ignored. You only ever bind the initial vales of your model, not the edited values (making your form rather pointless). Remove the hidden inputs!"

File Upload in ASP.NET MVC 5

I am unable to upload file in folder. I am not able to find the mistake. The UploadFile View returns on same view after uploading file.
Model Class:
public class Upload
{
public int UploadId { get; set; }
public string UploadTitle { get; set; }
public string UploadURL { get; set; }
}
Here is the Controller(FileUpload) Action:
public ActionResult UploadFile(HttpPostedFileBase file, Upload upload)
{
if (ModelState.IsValid)
{
if (file != null)
{
string fil = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("/Content/Uploads/Files"), fil);
file.SaveAs(path);
upload.UploadURL = "/Content/Uploads/Files/" + file.FileName;
}
db.Uploads.Add(upload);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(upload);
}
In my View:
#using (Html.BeginForm("UploadFile, "FileUpload", FormMethod.Post, new { enctype = "multipart/Form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="control-label col-md-2">
<label for="file">Upload Image for Slide:</label>
</div>
<div class="col-md-10">
<input type="file" name="file" id="file" style="width:50%" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Hi I have tried your same code its works for me.
Controller
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
string fil = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("/Content/Uploads/Files"), fil);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
return View("UploadFile");
}
View
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/Form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="control-label col-md-2">
<label for="file">Upload Image for Slide:</label>
</div>
<div class="col-md-10">
<input type="file" name="file" id="file" style="width:50%" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
I have found small mistake in you code in Html.BeginForm in action name " (double quotes is missing)
I forgot to mention the required field on UploadURL in above model class:
public class Upload
{
public int UploadId { get; set; }
public string UploadTitle { get; set; }
[Required]
public string UploadURL { get; set; }
}
Required Field validation on UploadURL field restricted the file upload here. I removed the Required field validation from the field.

ViewModel assigned an object, how can I pass that back into the Post?

So I have two methods:
public ActionResult Create(Guid id)
{
Assignment viewModel = new Assignment();
viewModel.Classroom = classroomRepository.GetByID(id);
return View(viewModel);
}
[HttpPost]
public ActionResult Create(Assignment assignment)
{
if (ModelState.IsValid)
{
assignmentRepository.Insert(assignment);
assignmentRepository.Save();
return RedirectToAction("Index");
}
return View(assignment);
}
As you can see, when I load up my Create page, I'm loading a Classroom into the viewModel. This works and displays the correct Classroom on the View.
My problem occurs when I POST to the Create method, my assignment object I pass in now doesn't include (it's NULL) Classroom that I passed in on GET.
EDIT ~ To Show View:
#model My_School_Book.Models.Assignment
#{
ViewBag.Title = "Create";
}
<div class="span9">
<div class="row-fluid">
<h1>Creating New Assignment:</h1>
<hr />
#using (Html.BeginForm("Create", "Assignment", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.ValidationSummary(true)
<div class="control-group">
#Html.LabelFor(model => model.Classroom.Name, "Classroom", new { #class = "control-label" })
<div class="controls">
<span style="font-size: 26px;">#Html.DisplayTextFor(model => model.Classroom.Name)</span>
</div>
</div>
<div class="control-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label" })
<div class="controls">
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="control-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label" })
<div class="controls">
#Html.TextAreaFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
</div>
<div class="control-group">
#Html.LabelFor(model => model.AssignedDate, new { #class = "control-label" })
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-calendar"></i></span>#Html.TextBoxFor(model => model.AssignedDate)
</div>
#Html.ValidationMessageFor(model => model.AssignedDate)
</div>
</div>
<div class="control-group">
#Html.LabelFor(model => model.DueDate, new { #class = "control-label" })
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-calendar"></i></span>#Html.TextBoxFor(model => model.DueDate)
</div>
#Html.ValidationMessageFor(model => model.DueDate)
</div>
</div>
<div class="control-group">
#Html.LabelFor(model => model.Weight, new { #class = "control-label" })
<div class="controls">
#Html.TextBoxFor(model => model.Weight, new { #class = "span2" })
#Html.ValidationMessageFor(model => model.Weight)
</div>
</div>
<div class="control-group">
#Html.LabelFor(model => model.Total, new { #class = "control-label" })
<div class="controls">
#Html.TextBoxFor(model => model.Total, new { #class = "span2" })
#Html.ValidationMessageFor(model => model.Total)
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary"><i class="icon-plus-6"></i> Create</button>
<i class="icon-back"></i> Cancel
</div>
}
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$("#AssignedDate").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
dateFormat: "DD MM d, yy",
minDate: -14,
onSelect: function (selectedDate) {
$("#DueDate").datepicker("option", "minDate", selectedDate);
}
});
$("#DueDate").datepicker({
dateFormat: "DD MM d, yy",
minDate: 0,
onSelect: function (selectedDate) {
$("#AssignedDate").datepicker("option", "maxDate", selectedDate);
}
});
});
</script>
}
You are only including Classroom.Name, thus on the form post nothing is there for the model binder to populate your model with.
Do you really need the classroom populated back though? What are you trying to accomplish?
If you need the ID simply write it out as:
#Html.HiddenFor(o=>o.Classroom.ClassroomId)
(or whatever the id is) and load it back up on the server side.
If you really need it there - you can write it out as inputs via
#Html.EditorFor(o=>o.Classroom)
That then allows the end user to modify it which I dont think you want, thus I'd use the ID (guid).
If you want that Classroom survive post then you need to add it to form in hiddenfield:
Just add this into form:
#Html.HiddenFor(m=m.Classroom.ClassroomId)
#Html.HiddenFor(m=m.Classroom.ClassroomName)
I ended up using a View Model:
public class AssignmentCreateData
{
public Guid ClassroomID { get; set; }
public String ClassroomName { get; set; }
public Assignment Assignment { get; set; }
}
and my controller looked like this:
public ActionResult Create(Guid id)
{
AssignmentCreateData viewModel = new AssignmentCreateData();
Classroom classroom = classroomRepository.GetByID(id);
viewModel.ClassroomID = classroom.ClassroomID;
viewModel.ClassroomName = classroom.Name;
viewModel.Assignment = null;
return View(viewModel);
}
[HttpPost]
public ActionResult Create(AssignmentCreateData viewModel)
{
if (ModelState.IsValid)
{
viewModel.Assignment.ClassroomID = viewModel.ClassroomID;
assignmentRepository.Insert(viewModel.Assignment);
assignmentRepository.Save();
return RedirectToAction("Index");
}
return View(viewModel);
}
Then my View includes:
#Html.HiddenFor(model => model.ClassroomID)

Resources