MVC validation not working as expected in popup window - asp.net-mvc

I'm trying to utilize the built-in validation in MVC and it doesn't appear to be working. If I leave the fields in my form empty I get back my "Successfully Saved." message.
Shouldn't the fields that are 'Required' be marked as required in the form?
Controller:
public ActionResult Create([DataSourceRequest] DataSourceRequest request, ACore.Asset assetForm)
{
var results = new
{
value = false,
Message = ""
};
if (ModelState.IsValid)
{
results = new
{
value = true,
Message = "Successfully Saved."
};
return Json(results);
}
results = new
{
value = false,
Message = "Please check the form values."
};
return Json(results);
}
View (condensed):
#using (Html.BeginForm("Create", "Asset", FormMethod.Post, new { id = "frmAsset"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="tempStyle">
<div class="editor-label fl">
#Html.LabelFor(model => model.AssetName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetName)
#Html.ValidationMessageFor(model => model.AssetName)
</div>
</div>
<div style="position: relative;">
<input type="button" value="Save" id="btnSave" />
</div>
JavaScript that handles my save:
var saveAsset = function (e) {
var form = $("#frmAsset");
$.ajax({
type: "POST",
url: "/Asset/Create",
data: $(form).serialize(),
success: function (data) {
if (data.value == true) {
alert(data.Message);
// Close popup window
var window = $('#AssetEditorPopUp').data("kendoWindow");
window.close();
// Refresh grid to show changes
$('#grid').data("kendoGrid").dataSource.read();
return;
}
alert(data.Message);
},
error: function () {
alert("There was an error editing the asset.");
}
});
};
Model:
public class Asset
{
[ScaffoldColumn(false)]
public int AssetId { get; set; }
[Required]
[Display(Name="Asset Name:")]
public string AssetName { get; set; }
public string AssetFormerName { get; set; }
public string Seg1Code { get; set; }
public string Seg3Code { get; set; }
public bool? ActiveFlag { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string AssetType { get; set; }
[Display(Name = "ZipCode:")]
[RegularExpression("([a-zA-Z0-9 .&'-]+)", ErrorMessage = "Enter only alphabets and numbers of First Name")]
public string ZipCode { get; set; }
}
This is what I get doing a POST rather than ajax.

your button is set to be of type button, it should be submit. you aren't firing the forms submit handler, so validation isn't being performed.
create your form like this:
#using (Html.BeginForm("Create", "Asset", FormMethod.Post, new { id = "frmAsset"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="tempStyle">
<div class="editor-label fl">
#Html.LabelFor(model => model.AssetName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetName)
#Html.ValidationMessageFor(model => model.AssetName)
</div>
</div>
<div style="position: relative;">
<input type="submit" value="Save" id="btnSave" />
</div>
Then you can use the following javascript:
$(function(){
$("#frmAsset").submit(function(evt){
var form = $(evt.currentTarget);
if(form.validate().isvalid()
{
// your handler here
}
evt.preventDefault(); // prevent the form from posting normally
return false;
};
};
I would look at the AJAX.BeginForm helper, it is more suited to what you are doing here.
nb. I haven't typed this in the ide, so i don't know if it is 100% valid, you will need to test it.

Related

ViewModel Contents are Null after Posting Form to Controller

So the ViewModel has 2 sets of data.
The CurrentDetails and UpdatedDetails. Both are instances of the same class which carries strings and whatnot inside etc.
This method has worked with all other views and models I've attempted with, but for THIS one instance, when the form is posted to the controller, its contents (CurrentDetails and UpdatedDetails) are both found to be null.
I've tried changing the parameter name from model to test and to other arbitrary things, but to no avail.
The one thing that worked (but is not a solution to me) is NOT having instances of the class inside the ViewModel, and just having the data there (but I don't see why I should be forced to do things this way.
Here's the controller:
[HttpPost]
public ActionResult FloristProfile(MerchantFloristProfileViewModel test)
{
if (!ModelState.IsValid)
return View(test);
using (var db = new ApplicationDbContext())
{
Florist florist = db.Florists.Find(MerchantBase.FloristID);
if (Request.Form["editSubmit"] != null)
{
florist.Name = test.UpdatedDetails.Name;
florist.Website = test.UpdatedDetails.Website;
db.SaveChanges();
return RedirectToAction("FloristProfile");
}
else if (Request.Form["photoSubmit"] != null)
{
if (test.CurrentDetails.File.ContentLength > 0)
{
CloudBlobContainer container = FlowerStorage.GetCloudBlobContainer();
string blobName = String.Format("florist_{0}.jpg", Guid.NewGuid().ToString());
CloudBlockBlob photoBlob = container.GetBlockBlobReference(blobName);
photoBlob.UploadFromStream(test.CurrentDetails.File.InputStream);
florist.LogoPath = blobName;
florist.isRendering = true;
db.SaveChanges();
return RedirectToAction("FloristProfile");
}
}
}
return Content("Invalid Request");
}
View:
#using (Html.BeginForm("FloristProfile", "Merchant", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#Html.HiddenFor(x => x.CurrentDetails.FloristID)
#Html.HiddenFor(x => x.CurrentDetails.Name)
#Html.HiddenFor(x => x.CurrentDetails.StaffCount)
#Html.HiddenFor(x => x.CurrentDetails.StoreCount)
#Html.HiddenFor(x => x.CurrentDetails.Website)
<div class="form-group">
#Html.LabelFor(x => x.UpdatedDetails.Name, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.TextBoxFor(x => x.UpdatedDetails.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.UpdatedDetails.Website, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.TextBoxFor(x => x.UpdatedDetails.Website, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="editSubmit" class="btn btn-success">Save</button>
</div>
</div>
}
ViewModel:
public class MerchantFloristProfileViewModel
{
public class FloristProfileDetails
{
public int FloristID { get; set; }
[Required(ErrorMessage = "Please Enter a Name")]
public string Name { get; set; }
[DataType(DataType.Url)]
[Required(ErrorMessage = "Please Enter a Website")]
public string Website { get; set; }
public int StoreCount { get; set; }
public int StaffCount { get; set; }
// For Picture Upload
public HttpPostedFileBase File { get; set; }
}
public FloristProfileDetails CurrentDetails;
public FloristProfileDetails UpdatedDetails;
}
Both CurrentDetails and UpdatedDetails in your MerchantFloristProfileViewModel model are fields, not properties (no getter/setter) so the DefaultModelBinder cannnot set the values. Change them to
public FloristProfileDetails CurrentDetails { get; set; }
public FloristProfileDetails UpdatedDetails { get; set; }
But you should not be sending all that extra data to the view, then sending it all back again unchanged. Apart from the extra overhead, any malicious user could alter the values in the hidden fields causing your app to fail. Just get the original from the repository again if you need it in the POST method

Adding/Update Related Data ASP.NET MVC 5

I'm new to programming so I'm still learning.
I need to add Items to Grocery from a single view. But I can't get the data to save.
When I hit save I don't get any exceptions, the page just loads but nothing is saved to the
database. Can I get some help/guidance as to what I am doing wrong?
Data Class
public class Grocery
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Item> Items { get; set; }
}
public class Item {
public int ItemId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
View Model
public class GroceryViewModel
{
public Grocery Grocery { get; set; }
public virtual Item Item { get; set; }
public GroceryViewModel(int GroceryId)
{
using (var db = new MyContext())
{
Grocery = db.Groceries
.Include("Items")
.SingleOrDefault(a => a.Id == GroceryId);
}
}
}
Controller
public ActionResult Edit(int GroceryId, GroceryViewModel groceryViewModel)
{
var model = new GroceryViewModel(GroceryId);
var plusItems = new Item
{
Name = groceryViewModel.Item.Name,
Description = groceryViewModel.Item.Description,
};
db.Items.Add(plusItems);
db.SaveChanges();
return RedirectToAction(model);
View
#model Project.Models.GroceryViewModel
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Groceries</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Item.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item.Name)
#Html.ValidationMessageFor(model => model.Item.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Item.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Item.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Add Item" />
</p>
</fieldset>
try
using (var db = new MyContext())
{
var grocery = db.Groceries.Single(a => a.Id == groceryId);
var plusItems = new Item
{
Name = groceryViewModel.Item.Name,
Description = groceryViewModel.Item.Description,
};
grocery.Items.Add(plusItems);
db.SaveChanges();
}

MVC model not bound to collection in POST

Visual Studio 2012
MVC 5.2.0
jQuery 2.1.1
jQuery UI Combined 1.10.4
Json.Net 6.0.3
Kendo UI MVC 2014.1.528
I've read through many similar posts. I've tried to apply what I've seen to no avail. I throw myself at feet of your keyboards for your mercy and help.
I have a survey-like site, so for simplicity here, I made up a sample project to duplicate the issue. I can upload that too.
I have a model with a child object of Address - no problemo there - it binds.
The model also has a collection of questions. It never binds on the post, and this is the issue here.
Lets start with models:
The Survey itself:
public class Survey
{
[ScaffoldColumn(false)]
public int Id { get; set; }
public string Name { get; set; }
[DisplayName("Phone #")]
[StringLength(15)]
[DataType(DataType.PhoneNumber)]
public string ContactMethodPhone { get; set; }
[DisplayName("Email")]
[StringLength(120)]
[EmailAddress]
public string ContactMethodEmail { get; set; }
public virtual Address Address { get; set; }
public virtual List<Question> Questions { get; set; }
}
and the address:
public class Address
{
[ScaffoldColumn(false)]
public int AddressId { get; set; }
[DisplayName("Address line 1")]
[Required]
[StringLength(200)]
public string Street { get; set; }
[DisplayName("Address line 2")]
[StringLength(200)]
public string Street2 { get; set; }
[DisplayName(" ")]
[StringLength(50)]
public string ApartmentNum { get; set; }
[DisplayName("Type")]
[StringLength(50)]
public string Tenement { get; set; }
[DisplayName("City")]
[Required]
[StringLength(200)]
public string City { get; set; }
[DisplayName("Province/State")]
[StringLength(20)]
public string State { get; set; }
[Required]
[DisplayName("Postal/Zip Code")]
[StringLength(10)]
public string MailCode { get; set; }
[DisplayName("Country")]
[StringLength(30)]
public string Country { get; set; }
[NotMapped]
public List<SelectListItem> Cities { get; set; }
[NotMapped]
public List<SelectListItem> Provinces { get; set; }
[NotMapped]
public List<SelectListItem> Countries { get; set; }
[NotMapped]
public List<SelectListItem> MailCodes { get; set; }
[NotMapped]
public List<SelectListItem> Tenements { get; set; }
}
and the questions:
public class Question
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[ScaffoldColumn(false)]
public int ImageID { get; set; } // Question Image
[DisplayName("Question: ")]
public string InformationIntakeGroupValue { get; set; } // Question: ie Did you graguate high school
public int ImageID_Topic { get; set; } // Topic Image
[DisplayName("Topic: ")]
public string InformationIntakeTopicValue { get; set; } // Topic: ie Education
[ScaffoldColumn(false)]
public string InformationIntakeTypeCode { get; set; } // Type of question (date, bool, text)
// below not filled by select;
// the key from the EntityAffilliateIntake record insert
public int PersonId { get; set; } // Person anwering question
// this is the user response area
[DisplayName("Answer: ")]
public string InformationIntakeValue { get; set; }
[DisplayName("Choice: ")]
public string InformationIntakeValueBool { get; set; }
[DisplayName("Date: ")]
public DateTime InformationIntakeValueDate { get; set; }
[ForeignKey("Survey")]
public int SurveyId { get; set; }
public virtual Survey Survey { get; set; }
}
(Note: fyi, I've tried the models without foreign keys as well - but perhaps it's not defined correctly)
The controller :
// GET: /Inquiry/Create
public ActionResult Create()
{
var geoIpData = Strings._download_serialized_json_data<GeoData>(StringConstants.UrlForGeoService);
SurveyModel = new Survey
{
Id=1,
Address = new AddressController().GetAddressModel(geoIpData.country, geoIpData.regionName, geoIpData.city, ""),
Questions = new QuestionController().GetQuestions(1).ToList()
};
return View(SurveyModel);
}
// POST: /Inquiry/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
public ActionResult Create([Bind(Include = "Id, Name, ContactMethodPhone, ContactMethodEmail, Address, Questions")] Survey survey)
{
if (ModelState.IsValid)
{
int i = 0;
}
if (survey.Address.Cities == null)
{
survey.Address.Cities = SurveyModel.Address.Cities;
survey.Address.Countries = SurveyModel.Address.Countries;
survey.Address.MailCodes = SurveyModel.Address.MailCodes;
survey.Address.Provinces = SurveyModel.Address.Provinces;
survey.Address.Tenements = SurveyModel.Address.Tenements;
}
if (survey.Questions == null)
{
survey.Questions = SurveyModel.Questions;
}
return View(survey);
}
The view:
#model BindCollection.Models.Survey
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
// I use <div class="container">, <fieldset> and <div class="row">
// instead of <div class="form-horizontal"> and <div class="form-group">
<div class="container">
<fieldset>
<legend></legend>
<h4>Survey</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id)
<div class="row">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2 col-md-2 col-lg-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
Your address information:<br />
<br />
</div>
</div>
#* no problem here with address *#
#{ var vddAddress = new ViewDataDictionary(ViewData) { TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = "Address" } };}
#Html.Partial("_AddressPartial", Model.Address, #vddAddress)
<hr />
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
How we can contact you? :<br />
<br />
</div>
</div>
<div class="row">
#Html.LabelFor(model => model.ContactMethodPhone, new { #class = "control-label col-sm-2 col-md-2 col-lg-2" })
<div class="col-sm-10 col-md-10 col-lg-10">
#Html.EditorFor(model => model.ContactMethodPhone)
#Html.ValidationMessageFor(model => model.ContactMethodPhone)
</div>
</div>
<div class="row">
#Html.LabelFor(model => model.ContactMethodEmail, new { #class = "control-label col-sm-2 col-md-2 col-lg-2" })
<div class="col-sm-10 col-md-10 col-lg-10">
#Html.EditorFor(model => model.ContactMethodEmail)
#Html.ValidationMessageFor(model => model.ContactMethodEmail)
</div>
</div>
<hr />
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
Some Questions<br />
<br />
</div>
</div>
#*Here is the evil one! Beware!*#
#{ var vddQuestions = new ViewDataDictionary(ViewData) { TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = "Questions" } };}
#Html.Partial("_QuestionsPartial", Model.Questions, #vddQuestions)
<hr />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</fieldset>
</div>
}
The address partial view is insignificant as there's no problem there.
Here's the partial view for the questions:
#model IEnumerable<BindCollection.Models.Question>
#using BindCollection
#using Kendo.Mvc.UI
#{
string CurrentTopic = string.Empty;
bool FirstTime = true;
}
#foreach (var item in Model)
{
if (CurrentTopic != item.InformationIntakeTopicValue)
{
CurrentTopic = item.InformationIntakeTopicValue;
if (!FirstTime)
{
FirstTime = false;
item.InformationIntakeTopicValue = string.Empty;
}
}
else
{
item.InformationIntakeTopicValue = string.Empty;
}
#Html.EditorFor(m=>item, "Question")
<br />
<br />
}
and, of course, I made an EditorTemplate for a question, as you can see a few lines above...
#model BindCollection.Models.Question
#Html.HiddenFor(m=>m.Id)
#{if (!string.IsNullOrWhiteSpace(Model.InformationIntakeTopicValue))
{
<hr />
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<br />
<br />
<h4>
#Html.DisplayFor(m => m.InformationIntakeTopicValue, new { #class = "control-label col-sm-10 col-md-10 col-lg-10" })
</h4>
<br />
</div>
</div>
}}
#*type of value to ask for is denoted by item.InformationIntakeTypeCode*#
<div class="row">
<div class="control-label col-sm-9 col-md-9 col-lg-9">
#Html.DisplayFor(m => m.InformationIntakeGroupValue, null)
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
#{
var outputBool = false;
var outputDate = false;
var outputText = false;
if(Model.InformationIntakeTypeCode.ToLower().Contains("date") )
{
outputDate = true;
}
else if (Model.InformationIntakeTypeCode.ToLower().Contains("bool"))
{
outputBool = true;
}
else if (Model.InformationIntakeTypeCode.ToLower().Contains("string"))
{
outputText = true;
}
}
#if(outputBool)
{
#(Html.Kendo().DropDownListFor(m => m.InformationIntakeValueBool)
.HtmlAttributes(new { style ="width: 100px;", id="InformationIntakeValueBool"+Model.Id.ToString() })
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Please Select...",
Value = "0"
},
new SelectListItem() {
Text = "Yes",
Value = "true"
},
new SelectListItem() {
Text = "No",
Value = "false"
}
}).Value("0")
)
}
#if(outputDate)
{
#(Html.Kendo().DatePickerFor(m => m.InformationIntakeValueDate)
.HtmlAttributes(new { style = "width: 100px;", id="InformationIntakeValueDate"+Model.Id.ToString() })
)
}
#if (outputText)
{
#Html.Kendo().AutoCompleteFor(m => m.InformationIntakeValue).HtmlAttributes(new { style = "width: 80%;", id="InformationIntakeValue"+Model.Id.ToString()})
}
</div>
</div>
So... When I POST, an odd thing occurs. All form values are passed, but the ones for Questions look strange:
Id 1
Name sally
Address.Street 123 Avenue Steet
Address.Street2 Building C
Address.Tenement Suite
Address.ApartmentNum 111
Address.City_input Sarnia
Address.City Sarnia
Address.State_input Ontario
Address.State Ontario
Address.Country_input Canada
Address.Country Canada
Address.MailCode_input N6B 2K0
Address.MailCode N6B 2K0
ContactMethodPhone 555-555-5555
ContactMethodEmail r#r.com
Questions.item.Id 1
Questions.item.InformationIntakeValueBool true
Questions.item.Id 2
Questions.item.InformationIntakeValueDate 2/4/2014
Questions.item.Id 3
Questions.item.InformationIntakeValue Speckled
Questions.item.Id 4
Questions.item.InformationIntakeValueBool true
Questions.item.Id 5
Questions.item.InformationIntakeValue Lightly Toasted
Questions.item.Id 7
Questions.item.InformationIntakeValueBool true
Questions.item.Id 8
Questions.item.InformationIntakeValue Nothing!
Questions.item.Id 6
Questions.item.InformationIntakeValueBool true
Questions.item.Id 9
Questions.item.InformationIntakeValueDate 6/29/2014
I thought, as I've seen in other posts, that the Question items should look like:
Questions[0].Id 1
Questions[0].InformationIntakeValueBool true
Questions[1].Id 2
Questions[1].InformationIntakeValueDate 2/4/2014
Questions[2].Id 3
Questions[2].InformationIntakeValue Speckled
So I'm not sure why mine looks like this.
On the server side, the Request only shows one variable for each:
Request.Form.Results View Expanding the Results View will enumerate the IEnumerable
[0] "__RequestVerificationToken" object {string}
[1] "Id" object {string}
[2] "Name" object {string}
[3] "Address.Street" object {string}
[4] "Address.Street2" object {string}
[5] "Address.Tenement" object {string}
[6] "Address.ApartmentNum" object {string}
[7] "Address.City_input" object {string}
[8] "Address.City" object {string}
[9] "Address.State_input" object {string}
[10] "Address.State" object {string}
[11] "Address.Country_input" object {string}
[12] "Address.Country" object {string}
[13] "Address.MailCode_input" object {string}
[14] "Address.MailCode" object {string}
[15] "ContactMethodPhone" object {string}
[16] "ContactMethodEmail" object {string}
[17] "Questions.item.Id" object {string}
[18] "Questions.item.InformationIntakeValueBool" object {string}
[19] "Questions.item.InformationIntakeValueDate" object {string}
[20] "Questions.item.InformationIntakeValue" object {string}
See the last 4 items? What about the other records?
I'm guessing that there's something strange with the ViewDataDictionary that I'm sending to the Question Partial View.
Any help would be appreciated. This should be simple...
Neither Partial Views or foreach statements contain the necessary information to properly bind collections. I always use EditorTemplates for everything. Especially since EditorTemplates will automatically iterate over a collection.
However, if you're bound and determined to use a loop, then use a for loop, and then index the model. In your case:
#for(int i = 0; i < Model.Count; i++)
{
if (CurrentTopic != Model[i].InformationIntakeTopicValue)
...
#Html.EditorFor(m => Model[i]) // don't have to specify the template name
// since it's the same name as the type
}
However, i'd just do this:
In your view, do this:
#*Here is the evil one! Beware!*#
#Html.EditorFor(m => m.Questions)
Then have your Question.cshtml as usual, which will automatically get iterated over by the EditorFor
However, at the top of the Question.cshtml (after the model declaration) add the following code, it's all that's necessary to achieve what you're trying to do. You don't need the partial view at all.
#{
if (ViewBag.CurrentTopic != Model.InformationIntakeTopicValue)
{
ViewBag.CurrentTopic = Model.InformationIntakeTopicValue;
}
else
{
Model.InformationIntakeTopicValue = string.Empty;
}
}

IEnumerable Property can't return the value

I have ViewModel
public class Magazine_ViewModel
{
public int MagId { get; set; }
public string MagNo { get; set; }
public IEnumerable<Titles_ViewModel> Titles { get; set; }
}
public class Titles_ViewModel
{
public int TitleId { get; set; }
public string TitleName { get; set; }
public int pos { get; set; }
}
in Controller i do like this
var viewModel = new Magazine_ViewModel
{
Titles = numberTitles
.Select(c => new Titles_ViewModel
{
TitleId = c.TitleId,
TitleName = c.Title.TitleText,
pos=c.position
}).ToList()
};
viewModel.MagNo = magazine.MagNo.ToString();
viewModel.MagId = magazine.Id;
when i check viewModel.Titles has n records which is right.
now in the view part
<div class="editor-label">
#Html.LabelFor(model => model.MagNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MagNo)
</div>
<div class="editor-field">
#Html.ListBox("wholeTitles")
<input type="button" name="add" id="add" value="add" onclick="addValue()" /><input type="button" name="remove" id="remove" value="remove" onclick="removeValue()"/>
#Html.ListBoxFor(model => model.Titles, new SelectList(Model.Titles, "TitleId", "TitleName"))
</div>
<p>
<input type="submit" value="Save" />
</p>
I add new Titles from first ListBox(wholeTitles) to second ListBox(Titles). Now the submit button is press and i want to add the new Titles to the database.
This is what i do in Post Action
[HttpPost]
public ActionResult EditTitle(Magazine_ViewModel magazineViewModel)
{
if (ModelState.IsValid)
{
var magazineTitles = new Magazine
{
Id = magazineViewModel.MagId,
NumberTitles = new List<NumberTitle>()
};
foreach (var numberTitle in magazineViewModel.Titles)
{
NumberTitle newNumberTitle = new NumberTitle();
newNumberTitle.MagazineId = magazineViewModel.MagId;
newNumberTitle.TitleId = numberTitle.TitleId;
newNumberTitle.position = 0;
unitOfWork.NumberTitleRepository.Insert(newNumberTitle);
}
}
return View();
}
but magazineViewModel.Titles shows null, I don't know what should I check to see why it is null value.
Your values not get posted back to the server. Use below in your View. This should post the titles back to the Server within the same ViewModel
for (var i = 0; i < Model.Titles.Count(); i++)
{
#Html.HiddenFor(m => m.Titles[i].TitleId)
#Html.HiddenFor(m => m.Titles[i].TitleName)
}

MVC 3 Dynamic Form Using a ViewModel

I have been trying for weeks to follow a couple tutorials on how to create a dynamic form giving the ability to add another "ingredient" to the form. Here is the article I tried to follow. http://www.joe-stevens.com/2011/07/24/asp-net-mvc-2-client-side-validation-for-dynamic-fields-added-with-ajax/
Right now Im just working on adding multiple recipeIngredients using the add link, but I will need to have both the "ingredientName", and "recipeIngredient" Amount able to be added when the link is clicked.
My problem is that when I run the app, the form for the recipeingredient has a 0 instead of an actual textbox. When I click add new ingredient, I am able to get a textbox to add, but when I type in an amount and click save, the model data isnt being passed to the controller..
I just dont even know where to begin with fixing this, I am not sure if I should be using a viewmodel or if Im going about this entirely wrong. Here is my database diagram http://i44.tinypic.com/xp1tog.jpg.
Here is my CreateView:
#model ViewModels.RecipeViewModel
#using Helpers;
<h2>CreateFullRecipe</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>
<script type="text/javascript">
$().ready(function () {
$("#add-recipeingredient").click(function () {
$.ajax({
url: '#Url.Action("GetNewRecipeIngredient")',
success: function (data) {
$(".new-recipeingredients").append(data);
Sys.Mvc.FormContext._Application_Load();
}
});
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Recipe</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Recipe.RecipeName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Recipe.RecipeName)
#Html.ValidationMessageFor(model => model.Recipe.RecipeName)
</div>
</fieldset>
<fieldset>
<legend>RecipeIngredients</legend>
<div class="new-recipeingredients">
#Html.EditorFor(model => model.RecipeIngredients)
</div>
<div style="padding: 10px 0px 10px 0px">
<a id="add-recipeingredient" href="javascript:void(0);">Add another</a>
</div>
</fieldset>
<div>
<input type="submit" value="CreateFullRecipe" />
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My editortemplateview for recipeingredient:
#model Models.RecipeIngredient
#using Helpers;
#using (Html.BeginAjaxContentValidation("form0"))
{
using (Html.BeginCollectionItem("RecipeIngedients"))
{
<div style="padding: 5px 0px 5px 0px">
#Html.LabelFor(model => model.Amount)
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => Model.Amount)
</div>
}
}
MY Controller relating methods:
[HttpGet]
public ActionResult CreateFullRecipe()
{
var recipeViewModel = new RecipeViewModel();
return View(recipeViewModel);
}
//
// POST: /Recipe/Create
[HttpPost]
public ActionResult CreateFullRecipe(RecipeViewModel recipeViewModel)
{
if (ModelState.IsValid)
{
db.Recipes.Add(recipeViewModel.Recipe);
db.SaveChanges();
int recipeID = recipeViewModel.Recipe.RecipeID;
for (int n = 0; n < recipeViewModel.RecipeIngredients.Count(); n++)
{
db.Ingredients.Add(recipeViewModel.Ingredients[n]);
int ingredientID = recipeViewModel.Ingredients[n].IngredientID;
recipeViewModel.RecipeIngredients[n].RecipeID = recipeID;
recipeViewModel.RecipeIngredients[n].IngredientID = ingredientID;
db.RecipeIngredients.Add(recipeViewModel.RecipeIngredients[n]);
db.SaveChanges();
}
return RedirectToAction("Index");
}
return View(recipeViewModel);
}
public ActionResult GetNewIngredient()
{
return PartialView("~/Views/Shared/IngredientEditorRow.cshtml", new Ingredient());
}
public ActionResult GetNewRecipeIngredient()
{
return PartialView("~/Views/Shared/_RecipeIngredientEditRow.cshtml", new RecipeIngredient());
}
My View Model:
public class RecipeViewModel
{
public RecipeViewModel()
{
RecipeIngredients = new List<RecipeIngredient>() { new RecipeIngredient() };
Ingredients = new List<Ingredient>() { new Ingredient() };
Recipe = new Recipe();
}
public Recipe Recipe { get; set; }
public IList<Ingredient> Ingredients { get; set; }
public IList<RecipeIngredient> RecipeIngredients { get; set; }
}
}
If there is any other information needed to help my problem out please let me know. This is really driving me crazy so I look forward to any help I can get
Thank you!
I would also like to mention that the controller post method createfullrecipe is for a pre defined list and it worked when I wasnt worried about giving the user the ability to add another ingredient, rather I just defaulted the form to have 2 ingredients and my view had this commented out code to create them. All I really want to do is get the viewmodel to pass the form data to the controller and I can handle the data like my createfullrecipe controller method does now.
#* #for (int n = 0; n < Model.Ingredients.Count(); n++)
{
<div class="editor-label">
#Html.LabelFor(model => model.Ingredients[n].IngredientName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Ingredients[n].IngredientName)
#Html.ValidationMessageFor(model => model.Ingredients[n].IngredientName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RecipeIngredients[n].Amount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.RecipeIngredients[n].Amount)
#Html.ValidationMessageFor(model => model.RecipeIngredients[n].Amount)
</div>
}*#
Here are my model classes:
public class Recipe
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
public string Description { get; set; }
public int? PrepTime { get; set; }
public int? CookTime { get; set; }
public string ImageURL { get; set; }
public virtual IList<RecipeTag> RecipeTags { get; set; }
public virtual IList<Rating> Ratings { get; set; }
public virtual IList<RecipeStep> RecipeSteps { get; set; }
public virtual IList<RecipeIngredient> RecipeIngredients { get; set; }
}
public class RecipeIngredient
{
public int RecipeIngredientID { get; set; }
public string IngredientDesc { get; set; }
public string Amount { get; set; }
public int RecipeID { get; set; }
public int? IngredientID { get; set; }
public virtual Recipe Recipe { get; set; }
public virtual Ingredient Ingredient { get; set; }
}
public class Ingredient
{
public int IngredientID { get; set; }
public string IngredientName { get; set; }
public virtual ICollection<RecipeIngredient> RecipeIngredients { get; set; }
}
There are lots of issues with your code. I prefer to go step by step in order to illustrate a simplified example that you could adapt to your needs.
Models:
public class RecipeViewModel
{
public Recipe Recipe { get; set; }
public IList<RecipeIngredient> RecipeIngredients { get; set; }
}
public class Recipe
{
public string RecipeName { get; set; }
}
public class RecipeIngredient
{
public int Amount { get; set; }
[Required]
public string IngredientDesc { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var recipeViewModel = new RecipeViewModel();
return View(recipeViewModel);
}
[HttpPost]
public ActionResult Index(RecipeViewModel recipeViewModel)
{
if (!ModelState.IsValid)
{
// there wre validation errors => redisplay the view
return View(recipeViewModel);
}
// TODO: the model is valid => you could pass it to your
// service layer for processing
return RedirectToAction("Index");
}
public ActionResult GetNewRecipeIngredient()
{
return PartialView("~/Views/Shared/EditorTemplates/RecipeIngredient.cshtml", new RecipeIngredient());
}
}
View (~/Views/Home/Index.cshtml):
#model RecipeViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#add-recipeingredient').click(function () {
$.ajax({
url: '#Url.Action("GetNewRecipeIngredient")',
type: 'POST',
success: function (data) {
$('.new-recipeingredients').append(data);
}
});
return false;
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div>
#Html.LabelFor(model => model.Recipe.RecipeName)
#Html.EditorFor(model => model.Recipe.RecipeName)
#Html.ValidationMessageFor(model => model.Recipe.RecipeName)
</div>
<fieldset>
<legend>RecipeIngredients</legend>
<div class="new-recipeingredients">
#Html.EditorFor(model => model.RecipeIngredients)
</div>
<div style="padding: 10px 0px 10px 0px">
<a id="add-recipeingredient" href="javascript:void(0);">Add another</a>
</div>
</fieldset>
<div>
<input type="submit" value="CreateFullRecipe" />
</div>
}
Editor template (~/Views/Shared/EditorTemplates/RecipeIngredient.cshtml):
#model RecipeIngredient
#using (Html.BeginCollectionItem("RecipeIngredients"))
{
<div>
#Html.LabelFor(model => model.Amount)
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => model.Amount)
</div>
<div>
#Html.LabelFor(model => model.IngredientDesc)
#Html.EditorFor(model => model.IngredientDesc)
#Html.ValidationMessageFor(model => model.IngredientDesc)
</div>
}

Resources