I am using kendoui grid with ClientTemplate to show textbox on each row of the grid.
I need to show validation messages on each empty textbox of the grid on click of a button outside the grid which will actually post the data.
View
#(Html.Kendo().Grid<MMM.Lumos.Entities.CustomEntities.OrganizationRiskViewModel>()
.Name("OrgRiskGrid")
.DataSource(dataSource => dataSource.Ajax()
.Model(model =>
{
model.Id(m => m.RiskId);
model.Id(m => m.RiskTierId);
model.Id(m => m.RiskTierKey);
model.Id(m => m.RiskKey);
})
.Read(read => read.Action("GetRiskType", "RiskTier").Data("getRiskTier"))
.Events(events =>
events.Error("error"))
)
.Columns(columns =>
{
columns.Bound(c => c.RiskName).Width(50);
columns.Bound(c => c.ATPTestMix).ClientTemplate(Html.Kendo().IntegerTextBox().Name("ATPTestMix").Min(0).HtmlAttributes(new { value = "", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
columns.Bound(c => c.VITestMix).ClientTemplate(Html.Kendo().IntegerTextBox().Name("VITestMix").Min(0).HtmlAttributes(new { value = "", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
columns.Bound(c => c.SMTestMix).ClientTemplate(Html.Kendo().IntegerTextBox().Name("SMTestMix").Min(0).HtmlAttributes(new { value = "", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
})
)
Model
public class OrganizationRiskViewModel
{
public int OrganizationId { get; set; }
public short RiskTierId { get; set; }
public string RiskTierName { get; set; }
public short RiskId { get; set; }
public string RiskName { get; set; }
[Required(ErrorMessage="ATP Test Mix is mandatory")]
public short ATPTestMix { get; set; }
[Required(ErrorMessage = "ATP Test Mix is mandatory")]
public short SMTestMix { get; set; }
[Required(ErrorMessage = "ATP Test Mix is mandatory")]
public short VITestMix { get; set; }
public string RiskTierKey { get; set; }
public string RiskKey { get; set; }
}
I tried setting the data annotations on the model to which the Grid is binded but unfortunately it didnt work.
Let me know if any one has the solution for the same.
<script type="text/javascript">
$(function () {
var form = $('#yourFormName');
form.data('validator').settings.ignore = ''; // default is ":hidden".
});
</script>
//Set DataAnnotation attributes
public IList<SelectListItem> SecretQuestion1IdList { get; set; }
[DisplayName("Answer to First Secret Question")]
[Required]
public string SecretQuestionAnswer1 { get; set; }
[DisplayName("Second Secret Question")]
[Required]
public int SecretQuestion2Id { get; set; }
public IList<SelectListItem> SecretQuestion2IdList { get; set; }
[DisplayName("Answer to Second Secret Question")]
[Required]
public string SecretQuestionAnswer2 { get; set; }
[Required]
public int TrustedDomainId { get; set; }
public IList<SelectListItem> TrustedDomain { get; set; }
}
#model ExternalUserManagement.Web.Mvc.Controllers.ViewModels.Register.RegisterPageViewModel
#{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="accountDetails" class="centre-container">
#using (Ajax.BeginForm("CreateAccount", "Register",
new AjaxOptions
{
UpdateTargetId = "accountDetails",
OnBegin = "windowHelper.displayWaitingDialog('Saving Registration Details, please wait...')",
OnComplete = "windowHelper.close()"
}))
{
<p class="message information">Register you details, then click submit.</p>
<div class="row">
#Html.LabelFor(m => m.FirstName, new { #class = "label" })
#Html.TextBoxFor(m => m.FirstName, new { #class = "input k-textbox" })
</div>
<div class="row">
#Html.LabelFor(m => m.LastName, new { #class = "label" })
#Html.TextBoxFor(m => m.LastName, new { #class = "input k-textbox" })
</div>
<div class="row">
#Html.LabelFor(m => m.CompanyEmail, new { #class = "label" })
#Html.TextBoxFor(m => m.CompanyEmail, new { #class = "input-left k-textbox" })
#
#(Html.Kendo().DropDownListFor(m => m.TrustedDomainId)
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.TrustedDomain)
.OptionLabel(" -- Please Select --")
.HtmlAttributes(new { #class = "input-right" })
)
</div>
<div class="row">
#Html.LabelFor(m => m.BirthDate, new { #class = "label" })
#Html.Kendo().DatePickerFor(m => m.BirthDate).HtmlAttributes(new { #class = "input" })
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestion1Id, new { #class = "label" })
#(Html.Kendo().DropDownListFor(m => m.SecretQuestion1Id)
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.SecretQuestion1IdList)
.OptionLabel(" -- Please Select --")
.HtmlAttributes(new { #class = "input" })
)
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestionAnswer1, new { #class = "label" })
#Html.TextBoxFor(m => m.SecretQuestionAnswer1, new { #class = "input k-textbox" })
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestion2Id, new { #class = "label" })
#(Html.Kendo().DropDownListFor(m => m.SecretQuestion2Id)
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.SecretQuestion2IdList)
.OptionLabel(" -- Please Select --")
.HtmlAttributes(new { #class = "input" }).AutoBind(true)
)
</div>
<div class="row">
#Html.LabelFor(m => m.SecretQuestionAnswer2, new { #class = "label" })
#Html.TextBoxFor(m => m.SecretQuestionAnswer2, new { #class = "input k-textbox" })
</div>
<div class="captcha row">
#Html.Label("Are you a human?", new { #class = "label" })
<br />
#Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
#Html.ValidationMessage("Invalid Characters")
</div>
<div class="row">
<div class="commands">
<button class="k-button" type="submit" title="Sumbit">
<img src="#Url.Content("~/Content/Images/Icons/disk.png")" alt="" />
Sumbit
</button>
</div>
</div>
}
</div>
Please have a look the following
Link:
http://macaalay.com/2014/02/15/enabling-asp-net-mvc-client-validation-for-kendo-ui-components/
Related
i am new to asp.net and i have a question. I have created a simple form fro sending sms, however my id always stays null. Can you please advise on what am i doing wrong? I used exactly the same form in my other page and it worked fine.
#model MessagingWebApplication.ViewModel.MessageViewModel
#{ ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Sms</h2>
#using (Html.BeginForm("MessageStatus", "Message"))
{
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.Message.Reciever)
#Html.TextBoxFor(m => m.Message.Reciever, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Reciever)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Sender)
#Html.TextBoxFor(m => m.Message.Sender, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Sender)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Message.Body)
#Html.TextBoxFor(m => m.Message.Body, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message.Body)
</div>
#Html.HiddenFor(m => m.Message.Id)
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary">Send</button>
}
My model
public class Message
{
[Key]
public int Id { get; set; }
[Required]
public string Sender { get; set; }
[Required]
public string Reciever { get; set; }
[Required]
public string Body { get; set; }
}
Method used for sending
public ActionResult Send(Message message)
{
var viewModel = new MessageViewModel
{
Message = new Message()
};
_context.Add(message);
_context.SaveChanges();
_messageSender.Send(message);
return View("MessageStatus", viewModel);
}
here _context.SaveChanges(); i get SqlException: Cannot insert the value NULL into column 'Id', table 'MyDatabase.dbo.Messages'; column does not allow nulls. INSERT fails.
My issue was that i had failed when updating the database so i just followed this How to delete and recreate from scratch an existing EF Code First database
I have an ASP.NET MVC model class like this:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Customer
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Customer()
{
this.Rates_Comments = new HashSet<Rates_Comments>();
}
[Required]
public double ID { get; set; }
[Required]
public string Marital_Status { get; set; }
[Required]
public string Gender { get; set; }
[Required]
[Range(5000,500000)]
public double Income { get; set; }
[Required]
public double Children { get; set; }
[Required]
public string Education { get; set; }
[Required]
public string Occupation { get; set; }
[Required]
public string Home_Owner { get; set; }
View:
<h2>Update My Account:</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-inline">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group" style="width:380px;">
<div class="form-group">
#Html.Label("Email-User Name", htmlAttributes: new { #class = "control-label col-md-10" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #style = "width:220px", #readonly = "readonly" } })
<br />
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("First Name", htmlAttributes: new { #class = "control-label col-md-10" })
<div class="col-md-10">
#Html.EditorFor(model => model.F_Name, new { htmlAttributes = new { #class = "form-control", #style = "width:220px" } })
<br />
#Html.ValidationMessageFor(model => model.F_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Last Name", htmlAttributes: new { #class = "control-label col-md-10" })
<div class="col-md-10">
#Html.EditorFor(model => model.L_Name, new { htmlAttributes = new { #class = "form-control", #style = "width:220px" } })
<br />
#Html.ValidationMessageFor(model => model.L_Name, "", new { #class = "text-danger" })
</div>
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Marital_Status,Gender,Income,Children,Education,Occupation,Home_Owner,Cars,Commute_Distance,Region,Age,Buy,OrderNumber")] Customer customer)
{
int[] Children = new int[] { 0, 1, 2, 3, 4, 5 };
ViewBag.OrderNumber = new SelectList(db.Orders, "OrderNumber", "OrderNumber");
ViewBag.Gender = new SelectList(db.Customers.Select(x => x.Gender).Distinct());
ViewBag.email = new SelectList(db.Customers.Select(x => x.Email).Distinct());
ViewBag.fn = new SelectList(db.Customers.Select(x => x.F_Name).Distinct());
ViewBag.ln = new SelectList(db.Customers.Select(x => x.L_Name).Distinct());
ViewBag.pas = new SelectList(db.Customers.Select(x => x.Pass).Distinct());
ViewBag.Marital_Status = new SelectList(db.Customers.Select(x => x.Marital_Status).Distinct());
ViewBag.Education = new SelectList(db.Customers.Select(x => x.Education).Distinct());
ViewBag.Occupation = new SelectList(db.Customers.Select(x => x.Occupation).Distinct());
ViewBag.Home_Owner = new SelectList(db.Customers.Select(x => x.Home_Owner).Distinct());
ViewBag.Cars = new SelectList(db.Customers.Select(x => x.Cars).Distinct());
ViewBag.Commute_Distance = new SelectList(db.Customers.Select(x => x.Commute_Distance).Distinct());
ViewBag.Region = new SelectList(db.Customers.Select(x => x.Region).Distinct());
ViewBag.Children = new SelectList(Children);
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.OrderNumber = new SelectList(db.Orders, "OrderNumber", "OrderNumber", customer.OrderNumber);
return View(customer);
}
My issue that because of the [Required] data annotations, I can't update one cell in my table for example, user have to access his account to edit it if he needs to, so he may only edit one filed, not all of it.
And due registration issue, all filed are required, so how to overcome this one?
I have a model Class
public partial class FEES
{
public FEES()
{
}
public long FEE_ID { get; set; }
public decimal AMOUNT { get; set; }
public int CURRENCY_ID { get; set; }
public string NAME { get; set; }
public virtual CURRENCIES CURRENCIES { get; set; }
}
ViewModel
public class FeesViewModel
{
public SelectList CurrenciesList { get; set; }
public FeesViewModelInput input { get; set; }
public class FeesViewModelInput
{
[HiddenInput]
public long FEE_ID { get; set; }
[Display(Name = "Amount")]
[Required(ErrorMessage = "Fee Amount Is Required!")]
[RegularExpression(#"^[0-9,.]+$", ErrorMessage = "Please enter proper currency format e.g. 2,500")]
public decimal AMOUNT { get; set; }
[Display(Name = "Currency")]
[Required(ErrorMessage = "Currency Is Required!")]
public int CURRENCY_ID { get; set; }
[Required(ErrorMessage = "Fee Name Is Required!")]
[Display(Name = "Fee Name")]
public string NAME { get; set; }
}
}
Small service for the ViewModel
public void createFees(FEES fee, FeesViewModel viewModel)
{
fee.FEE_ID = viewModel.input.FEE_ID;
fee.CURRENCY_ID = viewModel.input.CURRENCY_ID;
fee.NAME = viewModel.input.NAME.Trim();
}
I call the service and the ViewModel in my controller.
Controller
public ActionResult Create()
{
FeesViewModel fees = new FeesViewModel();
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
fees.FeeTypesList = new SelectList(_feetypesService.GetFeeTypes().Where(c => c.ACTION_STATUS != 2), "FEE_TYPE_ID", "FEE_TYPE_NAME");
return View();
}
[HttpPost]
public ActionResult Create(FeesViewModel fees)
{
try
{
if (ModelState.IsValid)
{
//check if values is duplicate
if (_feesService.GetFees().Where(c => c.ACTION_STATUS != 2).Any(c => c.NAME.ToLower().Trim() == fees.input.NAME.ToLower().Trim()))
{
this.AddNotification("Fee Name already exist.<br/> Kindly verify the data.", NotificationType.ERROR);
}
else
{
var fee = new BPP.CCSP.Admin.Web.BPPCCSPAdminFeesService.FEES();
var helper = new FeesService();
helper.createFees(fee, fees);
_feesService.AddFee(fee);
var notif = new UINotificationViewModel()
{
notif_message = "Record saved successfully",
notif_type = NotificationType.SUCCESS,
};
TempData["notif"] = notif;
return RedirectToAction("Index");
}
}
}
catch (Exception e)
{
this.AddNotification("Fees cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR);
}
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
return View(fees);
}
And the View
#model BPP.CCSP.Admin.Web.ViewModels.FeesViewModel
#{
//ViewBag.Title = "Create";
}
<div class=" box box-body box-primary">
#using (Html.BeginForm("Create", "Fees", FormMethod.Post, new { #class = "form-horizontal", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, null, new { #class = "text-danger" })
#*#Html.HiddenFor(model => model.faculty_activation_date, new { #Value = System.DateTime.Now })*#
<div class="row .col">
<div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Create Fee</div>
</div>
<div class="panel-body">
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.NAME, "Fee Name")
#Html.TextBoxFor(model => model.input.NAME, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.NAME), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.NAME, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.AMOUNT, "Amount")
#Html.TextBoxFor(model => model.input.AMOUNT, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.AMOUNT), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.AMOUNT, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.CURRENCY_ID, "Currency")
#*#Html.DropDownList("CURRENCY_ID", (IEnumerable<SelectListItem>)ViewBag.name, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })*#
#Html.DropDownListFor(x => x.input.CURRENCY_ID, Model.CurrenciesList, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.CURRENCY_ID, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.FEE_TYPE_ID, "Fee Type")
#Html.DropDownListFor(model => model.input.FEE_TYPE_ID, Model.FeeTypesList, "Please Select a Fee Type", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.FEE_TYPE_ID, null, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="panel-title">
<div class="form-actions no-color">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
}
When I clicked on the View (Create), I got this error
The CurrencyID is a DropDownList coming from CURRENCIES model class.
I have these questions:
Why am I getting this error and how do I resolve it.
How do I do ViewModel without mapping.?
Why am I getting this error and how do I resolve it.
Because the Model is not set in your view. It is null.
When the users visit the Create page, you need to make sure to present them with options in the dropdown. Therefore, you need to make sure you pass the model into the view during GET.
public ActionResult Create()
{
// your code and pass fees to your view.
return View(fees);
}
How do I do ViewModel without mapping. Any example please.
You can use AutoMapper NuGet package to do the mapping.
I am Creating View Model of Employee Class and strongly typed my Create View with the EmployeeViewModel. In future, I will add many classes in my View Model. But the problem is I am getting Gender Foreign Key Error. May be I am binding wrong values in Create Controller. Below is my code:
Create Controllers:
public ActionResult Create()
{
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeeViewModel employeeModel)
{
if (ModelState.IsValid)
{
db.Employees.Add(employeeModel.Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name", employeeModel.Employee.GenderId);
return View(employeeModel);
}
Create View:
#model WebApplication2.EmployeeViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Employee.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.GenderId, "GenderId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GenderId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.GenderId, "", 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>
}
Models:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public byte GenderId { get; set; }
public Gender Gender { get; set; }
}
public class Gender {
public byte Id { get; set; }
public string Name { get; set; }
}
View Model:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
}
I am trying to get an image file name and location saved into a database, using mvc 4. Can someone see where I am going wrong? I am only new to mvc, and building this for a client. I have bplace a break point on this line "if (Request.Files.Count > 0)", but it skips it and goes into my else statement.
public ActionResult Create2(FestivalVM model)
{
if (ModelState.IsValid != true)
{
if (model.SelectedFestivalType != -1)
{
//db.save stuff from create.
Festival Newfestival = new Festival();
Newfestival.EndDate = model.endDate.Date;
Newfestival.FestivalCounty = db.Counties.Where(p => p.ID == model.SelectedCounty).Single();
Newfestival.FestivalName = model.FestivalName;
Newfestival.Description = model.sDescription;
Newfestival.FType = db.FestivalTypes.Where(p => p.ID == model.SelectedFestivalType).Single();
Newfestival.StartDate = model.startDate.Date;
Newfestival.Location = model.Location;
Newfestival.FestivalTown = db.Towns.Where(p => p.ID == model.SelectedTown).Single();
Newfestival.UserID = WebSecurity.CurrentUserId;
if (Request.Files.Count > 0)
{
string fileName = Guid.NewGuid().ToString();
string serverPath = Server.MapPath("~\\Content\\FestivalLogo");
Bitmap newImage = new Bitmap(Request.Files[0].InputStream);
newImage.Save(serverPath + "\\" + fileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
model.festivalLogo = "Content/FestivalLogo/" + fileName + ".jpg";
db.Festivals.Add(Newfestival);
db.SaveChanges();
return RedirectToAction("Details", new {id = Newfestival.FestivalId});
}
else
{
db.Festivals.Add(Newfestival);
db.SaveChanges();
return RedirectToAction("Details", new { id = Newfestival.FestivalId });
}
}
ModelState.AddModelError("", "No Festival Type Picked");
}
model.County = db.Counties.ToDictionary(p => p.ID, q => q.Name);
model.FestivalType = db.FestivalTypes.ToDictionary(p => p.ID, q => q.FType);
model.FestivalType.Add(-1, "--- Add New Festival Type ---");
model.Towns = db.Towns.ToDictionary(p => p.ID, q => q.Name);
model.startDate = DateTime.Now;
model.endDate = DateTime.Now;
return View(model);
}
View- Edited Here
#model MyFestival.Models.FestivalVM
#{
ViewBag.Title = "Add a Festival";
Layout = "~/Views/Shared/Festival.cshtml";
}
<h2>Create Your Festival</h2>
<br />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<ol class="breadcrumb">
<li>Home</li>
<li class="active">Creating a Festival</li>
</ol>
<hr />
#Html.ValidationSummary(true, null, new{#class="alert alert-danger"})
<div class="form-group">
#Html.LabelFor(model => model.FestivalName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-info-sign"></i></span>
#Html.TextBoxFor(model => model.FestivalName, new { #class = "form-control", #style = "width:210px" })
</div>
#Html.ValidationMessageFor(model => model.FestivalName, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.startDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(model => model.startDate, new { #class = "form-control datepicker", #style = "width:250px" })
</div>
#Html.ValidationMessageFor(model => model.startDate, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.endDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(model => model.endDate, new { #class = "form-control datepicker", #style = "width:250px" })
</div>
<!--<input class="form-control datepicker" style="width:250px" name="endDate" placeholder="Please pick date..."/>-->
#Html.ValidationMessageFor(model => model.endDate, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Towns, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
#Html.DropDownListFor(p => p.SelectedTown, Model.Towns.Select(p => new SelectListItem()
{
Text = p.Value.ToString(),
Value = p.Key.ToString(),
Selected = false
}),
new
{
#class = "form-control",
#style = "width:210px",
placeholder = "---- Select a Town ----"
})
</div>
#Html.ValidationMessageFor(model => model.Towns, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.County, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
#Html.DropDownListFor(p => p.SelectedCounty, Model.County.Select(p => new SelectListItem()
{
Text = p.Value.ToString(),
Value = p.Key.ToString(),
Selected = false
}),
new
{
#class = "form-control",
#style = "width:210px"
})
</div>
#Html.ValidationMessageFor(model => model.County, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FestivalType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
#Html.DropDownListFor(p => p.SelectedFestivalType, Model.FestivalType.Select(p => new SelectListItem()
{
Text = p.Value.ToString(),
Value = p.Key.ToString(),
Selected = false
}),
new
{
#class = "form-control",
#style = "width:210px;",
#onchange = "checkaddnew();"
})
</div>
#Html.ValidationMessageFor(model => model.FestivalType, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.sDescription, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-info-sign"></i></span>
#Html.TextAreaFor(model => model.sDescription, new { #class = "form-control", #style = "width:210px;" })
</div>
#Html.ValidationMessageFor(model => model.sDescription, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-info-sign"></i></span>
#Html.TextAreaFor(model => model.Location, new { #class = "form-control", #style = "width:210px" })
</div>
#Html.ValidationMessageFor(model => model.Location, null, new { #style = "color:red;" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.festivalLogo, new{#class="control-label col-md-2"})
<div class="col-md-10">
<input type="file" id="imageFile" name="imageFile" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-info" />
#Html.ActionLink("Back to List", "Index", null, new { #class = "btn btn-danger" })
</div>
</div>
</div>
}
#Html.Partial("CreateFestivalType", new MyFestival.Models.FestivalTypeVM())
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$('#SelectedFestivalType').change(function () {
if ($(this).find(":selected").val() == -1) {
$('#myModal').modal('show');
}
});
});
</script>
<script type="text/javascript">
function ajaxResponse(data) {
alert("This Worked and the Data ID is: " + data.FestivalTypeID);
var newOption = "<option value='" + data.FestivalTypeID + "'>" + data.Name + "</option>";
$('#SelectedFestivalType').append(newOption);
$('#myModal').modal('hide');
$("#SelectedFestivalType option[value='" + data.FestivalTypeID + "']").attr("selected", "selected");
}
;
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#startDate").datepicker("setDate", '+1', { dateFormat: "dd/mm/yy" }).on('changeDate', function (ev) {
$(this).blur();
$(this).datepicker('hide');
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#endDate").datepicker("setDate", '+2', { dateFormat: "dd/mm/yy" }).on('changeDate', function (ev) {
$(this).blur();
$(this).datepicker('hide');
});
});
</script>
Model
public class Festival
{
[Key]
public int FestivalId { get; set; }
[Required]
[Display(Name = "Festival Name"), StringLength(100)]
[DisplayFormat(ApplyFormatInEditMode = true)]
public string FestivalName { get; set; }
[Required]
[Display(Name = "Start Date")/*, DataType(DataType.Date)*/]
[DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[Required]
[Display(Name = "End Date")/*, DataType(DataType.Date)*/]
[DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
[Display(Name = "Festival Location")]
[DisplayFormat(ApplyFormatInEditMode = true)]
public DbGeography Location { get; set; }
[Required]
[Display(Name = "County")]
[DisplayFormat(ApplyFormatInEditMode = true)]
public virtual County FestivalCounty { get; set; }
[Required]
[Display(Name = "Town")]
[DisplayFormat(ApplyFormatInEditMode = true)]
public virtual Town FestivalTown { get; set; }
[Required]
[Display(Name = "Festival Type")]
[DisplayFormat(ApplyFormatInEditMode = true)]
public virtual FestivalType FType { get; set; }
[Display(Name = "Festival Logo")]
[DataType(DataType.Upload)]
[DisplayFormat(ApplyFormatInEditMode = true)]
public string FestivalLogo { get; set; }
[Display(Name = "Description"), StringLength(200)]
public string Description { get; set; }
public ICollection<Events> Events { get; set; }
public IEnumerable<Events> EventsOrdered
{
get { return Events.OrderBy(e => e.EventsDate); }
}
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual UserProfile User { get; set; }
}
ViewModel
public class FestivalVM
{
public int FestivalID { get; set; }
[Required]
[Display(Name = "Town")]
[DisplayFormat(ApplyFormatInEditMode = true)]
public Dictionary<int, string> Towns { get; set; }
[Required]
[Display(Name = "County")]
[DisplayFormat(ApplyFormatInEditMode = true)]
public Dictionary<int, string> County { get; set; }
[Required]
[Display(Name = "Festival Type")]
[DisplayFormat(ApplyFormatInEditMode = true)]
public Dictionary<int, string> FestivalType { get; set; }
public int SelectedTown { get; set; }
public int SelectedCounty { get; set; }
public int SelectedFestivalType { get; set; }
[Required]
[Display(Name = "Festival Name"), StringLength(100)]
[DisplayFormat(ApplyFormatInEditMode = true)]
public string FestivalName { get; set; }
[Required]
[Display(Name = "Start Date")/*, DataType(DataType.Date)*/]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime startDate { get; set; }
[Required]
[Display(Name = "End Date")/*, DataType(DataType.Date)*/]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime endDate { get; set; }
public HttpPostedFileWrapper imageFile { get; set; }
[Display(Name = "Festival Logo")]
public string festivalLogo { get; set; }
public UserProfile UserID { get; set; }
[Display(Name = "Description"), StringLength(200)]
public string sDescription { get; set; }
[Required]
[Display(Name = "Location")]
public DbGeography Location { get; set; }
}
You can do some changes to allow posting data:
View
change #using (Html.BeginForm()) to this line: using (Html.BeginForm("Create2", "YourControllerName", FormMethod.Post, new {enctype="multipart/form-data"})) as you are posting data
Action
should be like this:
public ActionResult Create2(FestivalVM model, HttpPostedFileBase imageFile)
{
if (ModelState.IsValid != true)
{
if (model.SelectedFestivalType != -1)
{
//db.save stuff from create.
Festival Newfestival = new Festival();
Newfestival.EndDate = model.endDate;
Newfestival.FestivalCounty = db.Counties.Where(p => p.ID == model.SelectedCounty).Single();
Newfestival.FestivalName = model.FestivalName;
Newfestival.Description = model.sDescription;
Newfestival.FType = db.FestivalTypes.Where(p => p.ID == model.SelectedFestivalType).Single();
Newfestival.StartDate = model.startDate;
Newfestival.Location = model.Location;
Newfestival.FestivalTown = db.Towns.Where(p => p.ID == model.SelectedTown).Single();
Newfestival.UserID = WebSecurity.CurrentUserId;
if (Request.Files.Count > 0)
{
string fileName = Guid.NewGuid().ToString();
string serverPath = Server.MapPath("~\\Content\\FestivalLogo");
Bitmap newImage = new Bitmap(Request.Files["imageFile"].InputStream);
newImage.Save(serverPath + "\\" + fileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Newfestival.festivalLogo = "Content/FestivalLogo/" + fileName + ".jpg";
db.Festivals.Add(Newfestival);
db.SaveChanges();
return RedirectToAction("Details", new {id = Newfestival.FestivalId});
}
else
{
db.Festivals.Add(Newfestival);
db.SaveChanges();
return RedirectToAction("Details", new { id = Newfestival.FestivalId });
}
}
ModelState.AddModelError("", "No Festival Type Picked");
}
model.County = db.Counties.ToDictionary(p => p.ID, q => q.Name);
model.FestivalType = db.FestivalTypes.ToDictionary(p => p.ID, q => q.FType);
model.FestivalType.Add(-1, "--- Add New Festival Type ---");
model.Towns = db.Towns.ToDictionary(p => p.ID, q => q.Name);
model.startDate = DateTime.Now;
model.endDate = DateTime.Now;
return View(model);
}
I hope it will help