How to assign one variable and pass another with post in razor - asp.net-mvc

I want to take some info from my model, edit one variable and pass it to post function. Here is my model:
public class TaskInputModel
{
[Required]
[Display(Name = "Input Value")]
public decimal Value { get; set; }
public long InputId { get; set; }
public MetriceModelTaskShedule[] Tasks;
}
and this is my Index.cshtml:
#model MetriceWeb.Models.TaskInputModel
#foreach (var item in Model.Tasks)
{
using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => item.Task)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Value)
#Html.ValidationMessageFor(model =>model.Value)
</div>
#Html.Hidden("Model.InputId", Model.InputId)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
}
I'm receiving this like that:
[HttpPost]
public ActionResult Index(TaskInputModel model)
{
...
}
When I'm submitting only InputId has some value, Value is always 0. When i delete line: #Html.Hidden("Model.InputId", Model.InputId) Value is ok, but i don't know how to receive InputId. Can you tell me how can I do this?

Problem solved. I just had to use #Html.Hidden("InputId", Model.InputId) instead of #Html.Hidden("Model.InputId", Model.InputId)

Related

Using a one model to populate the dropdown for the view on another model

I've been striking out on how to handle this situation. I have a model, the project model, and it has numerous items that need to be dropdowns for the user to change the selected item in question. I started out simple with the ProjectType value, which should have the selectable values populated form the ProjectTypes table. Here is the ViewModel:
public class ProjectViewModel
{
public APT_Projects Project { get; set; }
public System.Linq.IQueryable<APT_ProjectTypes> projecttypes { get; set; }
public APT_ClientTypes ClientTypes {get; set;}
}
Here is the controller:
public ActionResult Edit(int id = 0)
{
APT_Projects apt_projects = db.APT_Projects.Find(id);
if (apt_projects == null)
{
return HttpNotFound();
}
ProjectViewModel Project = new ProjectViewModel();
var apt_projecttypes = from a in db.APT_ProjectTypes
select a;
Project.Project = apt_projects;
Project.projecttypes = apt_projecttypes;
return View(Project);
}
and finally the view:
#model APTII_MVC.ViewModel.ProjectViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>APT_Projects</legend>
<div class="editor-label" style="float: left; width: 500px;" >
#Html.LabelFor(model => model.Project.Project_ID)
</div>
<div class="editor-field" style="float: left; width: 500px;" >
#Html.EditorFor(model => model.Project.Project_ID)
#Html.ValidationMessageFor(model => model.Project.Project_ID)
</div>
<div class="editor-label"">
#Html.LabelFor(model => model.Project.ProjectType_ID)
</div>
<div class="editor-field"">
#Html.DropDownListFor(model => model.Project.ProjectType_ID, Model.projecttypes)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
When I do it in this manner, .net doesn't like the Drowpdownlistfor, but I'm unclear how to use these values in a manner that the dropdownlistfor would accept. What is my mistake?
Edit: Relevent Error for the Dropdownlistfor.
'System.Web.Mvc.HtmlHelper<ViewModel.ProjectViewModel>' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' has some invalid arguments c:\Visual Studio 2012\Projects\Test_MVC\Test_MVC\Views\Project\Edit.cshtml
you might need a List<SelectListItem> or SelectList().. so try converting your projecttypes object to
#Html.DropDownListFor(model => model.Project.ProjectType_ID, new SelectList(Model.projecttypes,"ID","Type")
or edit your viewmodel to
public SelectList projecttypes { get; set; }
and your controller code to
Project.projecttypes = new SelectList(db.APT_ProjectTypes,"ID","Type");
just guessing on your value/text field names

How to customize ASP.net MVC jquery unobtrusive validation message display

by default MVC use jquery unobtrusive validation lib to show validation message at client side. suppose i have small form with two textbox for first name and last name. when click submit button then client side validation will fire and display all validation message at once. but i want to display validation message one by one. now tell me where to customize the code and what code need to add or modify in js to make it possible.
here is my small sample code
namespace MVC_myfirst_Mvcapplication.Models
{
public class Person
{
public int ID { get; set; }
[Required]
[StringLength(30)]
public string First { get; set; }
[Required]
[StringLength(30)]
public string Last { get; set; }
public DateTime Birthdate { get; set; }
}
public class PersonContext : DbContext
{
public DbSet<Person> People { get; set; }
}
}
Controller : PersonController.cs
public class PersonController : Controller
{
PersonContext db = new PersonContext();
//
// GET: /Person/
public ActionResult Index()
{
var People = db.People.ToList();
return View(People);
}
//
// GET: /Person/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Person/Create
[HttpPost]
public ActionResult Create(Person Person)
{
db.People.Add(Person);
db.SaveChanges();
return RedirectToAction("Index");
}
}
View:
#model MVC_myfirst_Mvcapplication.Models.Person
#{
ViewBag.Title = "Create";
}
<h2>Create</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>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.First)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.First)
#Html.ValidationMessageFor(model => model.First)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Last)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Last)
#Html.ValidationMessageFor(model => model.Last)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Birthdate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Birthdate)
#Html.ValidationMessageFor(model => model.Birthdate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
tell me which code i need to change in js to show validation message one-by-one in a specific div? thanks

ASP.NET MVC bool value returned from the view is 1 or 0

I am using ASP.NET MVC, and I have some problems using a CheckBoxFor. Here is my problem:
I have the following code in the view:
#Html.CheckBoxFor(model => model.stade, new { #id = "stade" })
model.stade is of type bool. In my controller, I have:
//Editar
[HttpPost]
public ActionResult InvoiceType(int Id, string Name, string Code, string Stade)
{
clsInvoiceTypea Model = new clsInvoiceType();
Model.Id = Id;
Model.Name = Name;
Model.Code = Code;
Model.Stade = stade== "1" ? true : false;
return PartialView(Model);
}
I get an error, because when Model.Stade is submitted to the view the value is 1 or 0, and I get an error saying "Can not recognize the string as a valid Boolean", but if Model.stade is boolean why the model is submitted to the view like 0 or 1? How I can I resolve this?
Here goes my solution -
Let your Model be -
public class clsInvoiceTypea
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public bool stade { get; set; }
}
Let your HttpGet Action be -
public ActionResult GetInvoice()
{
clsInvoiceTypea type = new clsInvoiceTypea();
return View(type);
}
And the corresponding view -
#model YourValidNameSpace.clsInvoiceTypea
#{
ViewBag.Title = "GetInvoice";
}
<h2>GetInvoice</h2>
#using (Html.BeginForm("SubmitData","Home",FormMethod.Post)) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>clsInvoiceTypea</legend>
<div class="editor-label">
#Html.LabelFor(model => model.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.Code)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Code)
#Html.ValidationMessageFor(model => model.Code)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.stade)
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.stade)
#Html.ValidationMessageFor(model => model.stade)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Let the following be your HttpPost Action -
[HttpPost]
public ActionResult SubmitData(clsInvoiceTypea model)
{
return View();
}
When you run the code, you will get following view -
When you select the checkbox and hit the create button, if you put a breakpoint on POST method and check the value, you will get true.

How do you post data to joined tables - Using EF 5, ASP.NET MVC 4

I am new to MVC 4 and up to this point I have been retrieving data from one table and saving back to the same table. Now I have data from joined tables and need to save back to the same joined tables. I created a new model and created the get controller but when I try to save I get an error. Any constructive help would be appreciated.
Model
public partial class JoinClass
{
public string Name { get; set; }
public int EEID { get; set; }
public string Category { get; set; }
public int Points { get; set; }
public string Programs { get; set; }
public DateTime EntryDate { get; set; }
public DateTime Quarter { get; set; }
}
Controller
public ActionResult Create()
{
ViewBag.VBQuarter = new SelectList(db.Quarter2, "Id_Quarter2", "Quarter");
ViewBag.VBEEID = new SelectList(db.Users2, "Id_Users2", "EEID");
ViewBag.FK_Programs = new SelectList(db.Programs, "Id_Programs", "Programs");
ViewBag.EntryDate = DateTime.Now;
return View();
}
//
// POST:
[HttpPost]
public ActionResult Create(JoinClass joinclass)
{
if (ModelState.IsValid)
{
db.JoinClass.Add(joinclass);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(joinclass);
}
View
#model 2014_V4.Models.JoinClass
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
<fieldset>
<legend>Points</legend>
<div class="editor-label">
Quarter
</div>
<div class="editor-field">
#Html.DropDownList("VBQuarter")
</div>
<div class="editor-label">
User
</div>
<div class="editor-field">
#Html.DropDownList("VBEEID")
</div>
<div class="editor-label">
Programs
</div>
<div class="editor-field">
#Html.DropDownList("FK_Programs", String.Empty)
</div>
<div class="editor-label">
Points
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Points)
</div>
<div class="editor-label">
Entery Date
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.EntryDate, new {#Value = ViewBag.EntryDate, #readonly="readonly" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Your problem is in constructor of JoinClass. You should not initialize virtual navigation properties collection with new HashSet<T>. Entity framework use its own collection type - EntityCollection<T>. You should not initialize navigation property collections at all.
PS: It is good practice to use special viewmodels with views and pass data from viewmodels to entity models explicit.

ICollection from ViewModel showing up as null, modelstate is not valid in MVC4

I have the following viewModel:
public class CreateCardViewModel
{
[HiddenInput(DisplayValue = false)]
public int SetId { get; set; }
[Required]
public ICollection<Side> Sides { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DateCreated { get; set; }
[Required]
public bool IsReady { get; set; }
}
And the following actions defined for Create:
[HttpGet]
public ActionResult Create(int setId)
{
var model = new CreateCardViewModel();
// attach card to current set
model.SetId = setId;
// create a new Side
var side = new Side() {Content = "Blank Side"};
// Add this to the model's Collection
model.Sides = new Collection<Side> { side };
return View(model);
}
[HttpPost]
public ActionResult Create(CreateCardViewModel viewModel)
{
if (ModelState.IsValid)
{
var set = _db.Sets.Single(s => s.SetId == viewModel.SetId);
var card = new Card {Sides = viewModel.Sides};
set.Cards.Add(card);
_db.Save();
}
return View(viewModel);
}
When I try to create a new card, the Sides property of the viewModel is null, so the ModelState is coming up as null. I can't quite figure out why that initial Side isn't getting passed with the model.
My View looks like this:
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>CreateCardViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.SetId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SetId)
#Html.ValidationMessageFor(model => model.SetId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DateCreated)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DateCreated)
#Html.ValidationMessageFor(model => model.DateCreated)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsReady)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IsReady)
#Html.ValidationMessageFor(model => model.IsReady)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
There's nothing in your View that is bound to the Sides property of your ViewModel. Without anything in the form to hold the value of that property, it will be null when model binding occurs. You'll need to somehow capture the Side in your form - how are you adding to/removing from this property? Via user interaction that should take place on the form?
Try adding a second argument on Create() of type ICollection<Side> and see if that gets anything passed to it.

Resources