Postback Contains No Model Data - asp.net-mvc

I have a form that was not receiving any of my model information on the postback. I have tried to comment out more and more to make it simple so I can see when it works and so far I am having no luck. I have commented out most of the complex parts of the form and model so I do not know why I am having issues.
Below is the controller functions to show the form and to post it
public ActionResult MassEmail()
{
IEmailTemplateRepository templates = new EmailTemplateRepository();
IEmailFromAddressRepository froms = new EmailFromAddressRepository();
IEmployeeRepository emps = new EmployeeRepository();
List<ProductVersion> vers = new List<ProductVersion>();
MassEmailViewModel vm = new MassEmailViewModel();
vers = productVersionRepository.All.OrderBy(o => o.Description).ToList();
foreach (Employee e in emps.Employees.Where(o => o.Department == "Support" || o.Department == "Professional Services").OrderBy(o => o.Name))
{
if (e.Email != null && e.Email.Trim() != "")
{
vm.BCCAddresses = vm.BCCAddresses + e.Email + ",";
}
}
if (vm.BCCAddresses != "")
{
vm.BCCAddresses = vm.BCCAddresses.Substring(0, vm.BCCAddresses.Length - 1);
}
ViewBag.PossibleCustomers = customerRepository.All.OrderBy(o => o.CustomerName);
ViewBag.PossibleTemplates = templates.All.OrderBy(o => o.Description);
ViewBag.PossibleFromAddresses = froms.All.OrderBy(o => o.Description);
ViewBag.PossibleClasses = scheduledClassRepository.All.OrderByDescending(o => o.ClassDate).ThenBy(o => o.ClassTopic.Description);
vm.CCAddresses = "bclairmont#harrisworld.com";
//vm.Attachments = "";
vm.Body = "";
vm.Subject = "";
vm.ToAddresses = "";
vm.EmailFromAddressID = 1;
return View(vm);
}
[HttpPost]
public ActionResult MassEmail(MassEmailViewModel vm)
{
IEmailFromAddressRepository froms = new EmailFromAddressRepository();
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress(froms.Find(vm.EmailFromAddressID).Email);
string[] toAddresses = vm.ToAddresses.Split(',');
for (int i = 0; i < toAddresses.GetUpperBound(0); i++)
{
message.To.Add(new System.Net.Mail.MailAddress(toAddresses[i]));
}
string[] CCAddresses = vm.CCAddresses.Split(',');
for (int i = 0; i < CCAddresses.GetUpperBound(0); i++)
{
message.To.Add(new System.Net.Mail.MailAddress(CCAddresses[i]));
}
string[] BCCAddresses = vm.BCCAddresses.Split(',');
for (int i = 0; i < BCCAddresses.GetUpperBound(0); i++)
{
message.To.Add(new System.Net.Mail.MailAddress(BCCAddresses[i]));
}
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
message.Subject = vm.Subject;
message.Body = vm.Body;
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
message.Attachments.Add(new Attachment(file.InputStream, file.FileName));
}
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Send(message);
return RedirectToAction("MassEmail");
}
Next is the code for my View
#model TRIOSoftware.WebUI.Models.MassEmailViewModel
#{
ViewBag.Title = "MassEmail";
}
#using (Html.BeginForm())
{
<h1 class="align-right">Mass E-Mail</h1>
<br />
<br />
<div>
<div class="editor-label" style="float:left; width:90px">
From
</div>
<div class="editor-field" style="float:left">
#Html.DropDownListFor(model => model.EmailFromAddressID,
((IEnumerable<TRIOSoftware.Domain.Entities.EmailFromAddress>)
ViewBag.PossibleFromAddresses).OrderBy(m => m.Description).Select(option => new
SelectListItem
{
Text = option.Description.ToString(),
Value = option.ID.ToString(),
Selected = (Model != null) && (option.ID == Model.EmailFromAddressID)
}), "Choose...")
</div>
</div>
<div class= "TagitEmailAddress" style="width:100%">
<div class="editor-label" style="float:left; clear:left; width:90px">
To
</div>
<div class="editor-field" style="float:left; width:88%">
#Html.TextBoxFor(model => model.ToAddresses, new { #class = "TagTextBox" })
</div>
</div>
<div class= "TagitEmailAddress" style="width:100%">
<div class="editor-label" style="float:left; clear:left; width:90px">
CC
</div>
<div class="editor-field" style="float:left; width:88%">
#Html.TextBoxFor(model => model.CCAddresses, new { #class = "TagTextBox" })
</div>
</div>
<div class= "TagitEmailAddress" style="width:100%">
<div class="editor-label" style="float:left; clear:left; width:90px">
<input type="button" id="BCC" value="BCC" class="btn"/>
</div>
<div class="editor-field" style="float:left; width:88%">
#Html.TextBoxFor(model => model.BCCAddresses, new { #class = "TagTextBox" })
</div>
</div>
<div style="width:100%">
<div style="float:left; clear:left; width:90px">
<input type="button" id="Subject" value="Subject" class="btn"/>
</div>
<div style="float:left; width:88%">
#Html.TextBoxFor(model => model.Subject, new { id = "SubjectText", style =
"width:100%" })
</div>
</div>
<div style="width:100%">
<div style="clear:left; float:left; width:100%;">
<div class="editor-field" style="float:left; width:100%;">
#Html.TextAreaFor(model => model.Body, new { id = "BodyText" })
</div>
</div>
</div>
<br />
<br />
<br />
<p style="clear:both">
<input type="submit" value="Send E-Mail" class="btn btn-primary"/>
</p>
<div id="DefaultEmailText">
<div class="editor-label" style="float:left; width:150px">
E-Mail Template
</div>
<div class="editor-field" style="float:left; padding-left:10px">
#Html.DropDownList("EmailTemplate",
((IEnumerable<TRIOSoftware.Domain.Entities.EmailTemplate>)
ViewBag.PossibleTemplates).Select(option => new SelectListItem
{
Text = option.Description,
Value = option.ID.ToString(),
Selected = false
}), "Choose...", new { ID = "Template", style = "width:200px" })
</div>
</div>
}
#section sidemenu {
#Html.Action("EmailsSideMenu", "Admin")
}
<script type="text/javascript">
var TemplateSubject = "";
var TemplateBody = "";
$(document).ready(function () {
$('#attach').MultiFile({
STRING: {
remove: '<i style="color:Red" class="icon-remove-sign"></i>'
}
});
$(".TagTextBox").tagit();
$("#BodyText").cleditor({
width: 800,
height: 400
});
$("#DefaultEmailText").dialog({
autoOpen: false,
height: 150,
width: 250,
title: "Default Subject / Body",
modal: true,
buttons: {
OK: function () {
var selectedTemplate = $("#DefaultEmailText #Template").val();
if (selectedTemplate != null && selectedTemplate != '') {
$.getJSON('#Url.Action("GetTemplate", "EmailTemplates")', { id:
selectedTemplate }, function (template) {
$("#SubjectText").val(template[0].Subject);
$("#BodyText").val(template[0].Body).blur();
});
}
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#Subject').click(function () {
$("#DefaultEmailText").dialog("open");
});
});
</script>
When I submit I get all null values except for the EmailFromAddressID which is 0 even though ti gets defaulted ot 1 when the view loads.
Any ideas?
EDIT____________________________________
I looked in DevConsole of Chrome and under network I coudl see my post request. Below is the detailed informaiton it contained. It looks to me liek the data did get sent to the server so I do not knwo why the server cant fill in my Model class
Request URL:http://localhost:53730/Customers/MassEmail
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type:application/x-www-form-urlencoded
Origin:http://localhost:53730
Referer:http://localhost:53730/Customers/MassEmail
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko)
Chrome/24.0.1312.52 Safari/537.17
Form Dataview sourceview URL encoded
EmailFromAddressID:1
ToAddresses:
CCAddresses:bclairmont#harrisworld.com
BCCAddresses:adunn#harrisworld.com,bclairmont#harrisworld.com,
bkelly#harrisworld.com,bhackett#harrisworld.com,jwade#harrisworld.com,
krichter#harrisworld.com,mroy-waters#harrisworld.com,
nburckhard#harrisworld.com,rlibby#harrisworld.com
Subject:Testing
Body:
Here is the class that gets passed back and forth from the clien tto server in case that helps
public class MassEmailViewModel
{
//public MassEmailViewModel()
//{
// ComplexQuery = new CustomerQueryViewModel();
//}
public int EmailFromAddressID;
// public CustomerQueryViewModel ComplexQuery;
public string ToAddresses;
public string CCAddresses;
public string BCCAddresses;
public string Subject;
public string Body;
//public string Attachments;
}

The DefaultModelBinder needs public properties not public fields.
Change your fields to properties and it should work:
public class MassEmailViewModel
{
public int EmailFromAddressID { get; set; }
public string ToAddresses { get; set; }
public string CCAddresses { get; set; }
public string BCCAddresses { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}

1) Have you tried specifing the route of the controller to which the model will be submited?. I mean, declaring the form like this:
#using (Html.BeginForm("YourAction","YourController", FormMethod.Post))
2) Why dont you just create a simple "Get" action that returns the strongly typed view and a "Post" action that receives the same model with the information you added in the view. Once you make work that, you can begin adding extra code so it is easy to trobleshoot the problem.
3) Make sure all of your helpers are inside the form.
4) Have you configured routing rules that can be making your post being redirected to another area, controller or action?

Related

How can i pass multiple radio button values to controller in ASP.NET MVC?

I've a model that contains 3 tables in my view.
public class InExam
{
public AutoTests TheTest { get; set; }
public List<InTest> TheQuestions { get; set; }
public IEnumerable<Result> SingleQuee { get; set; }
}
First one made to get the detailed page, like "admin/AutoTests/id"
Second one made to get a list of questions linked to the page
Third one is to save radio button strings to post it back into the controller
my plan is to get (say) 20 questions that are linked with the detailed page, Adding 4 radio buttons for each question, and post back every selected button to the controller.
my view form :
#using (Html.BeginForm("Test", "Exams", new { id = Model.TheTest.id }, FormMethod.Post))
{
foreach (var item in Model.TheQuestions)
{
Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();
<div class="container" style="padding-top:50px;direction:rtl;">
<h4 style="text-align:right;font-weight:bold;">#item.Question</h4>
<div class="container">
<div class="row" style="direction:rtl;">
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "1" })
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "2" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer2</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "3" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer3</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "4" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer4</h5>
</div>
</div>
#Html.HiddenFor(m => singleQuee.Question)
</div>
</div>
</div>
}
<button class="btn botton" type="submit" onclick="return confirm('');">END</button>
}
i used this line "Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();" in my view because i can't use tuple foreach ( C# ver. 5 )
This is my controller code :
[HttpGet]public ActionResult Test(int? id)
{
using (KafoEntities db = new KafoEntities())
{
InExam model = new InExam();
model.TheTest = db.AutoTests.Where(x => x.id == id).FirstOrDefault();
model.TheQuestions = db.InTest.Where(x => x.UserEmail == currentUser.Email && x.ExamId == model.TheTest.id).OrderByDescending(x => x.id).Take(Convert.ToInt32(model.TheTest.QuestionsNumber)).ToList();
model.SingleQuee = db.Result.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Test(int? id, List<Result> singleQuee)
{
using (KafoEntities db = new KafoEntities())
{
int result = 0;
foreach (Result item in singleQuee)
{
Result sets = db.Result.Where(x => x.id == item.id).FirstOrDefault();
sets.Question = item.Question;
db.SaveChanges();
var check = db.InTest.Where(x => x.Question == item.Question).FirstOrDefault();
if (check != null)
{
if (item.Question == "1")
{
result++;
}
}
}
return RedirectToAction("Results", "Exams", new { Controller = "Exams", Action = "Results", id = done.id });
}
}
I first save the new string that came from the radio button value into the result record, then i call it back in the if condition to check it's value
The problem here is i get a
Object reference not set to an instance of an object.
when i post the test, it means that the list is empty, so i need to know what makes the radio buttons not working,
Thanks.
If you want to bind a List of object in Mvc, you should name the controller like "ModelName[indx].PropertyName". In your case it should be "singleQuee[0].Question".
Code Sample
var Indx = 0;
foreach (var item in Model.TheQuestions)
{
.....
var radioName = $"singleQuee[{Indx}].Question";
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
<input type="radio" name="#radioName" value="1" />
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
.....
}
Action Method

Ajax begin form db record with mvc

I created a form. I want to do a post save method.
He records but records the same data twice. How can I solve this problem?
I have to solve the double registration problem. I'm pushing the button once. When I go through Debug step by step, it goes twice on the same line. When I control the db as a top-down, I see that you double-logged.
HTML:
<div class="portlet-body form">
#using (Ajax.BeginForm("TalepTurKaydet", "MasterEducationController",
new AjaxOptions { HttpMethod = "post", OnSuccess = "TalepTurKaydet" },
new { #class = "" }))
{
#Html.ValidationSummary(true)
<div class="form-body">
<div class="row">
<div class="col-md-12" style="margin-left: 20px">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Açıklama: </label>
<div class="col-md-9">
<textarea id="Aciklama" name="Aciklama" class="col-md-12" style="resize: none;" rows="5" placeholder="Açıklama"></textarea>
</div>
</div>
</div>
<div class="clearfix"></div><br /><br />
</div>
<div class=" form-actions right">
<button type="button" class="btn green btnPrevious"><i class="fa fa-angle-double-left"></i>Geri</button>
<button id="talepOlustur" type="submit" class="btn blue"><i class="fa fa-check"></i> Talep Oluştur</button>
</div>
</div>
}
</div>
Controller:
public ActionResult MezuniyetBilgiKaydet(MezuniyetBilgi model)
{
List<MezuniyetBilgi> list = null;
model.KullaniciId = GetUye().kullaniciID;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ApiAdress.API_URL);
var responseTask = client.PostAsJsonAsync("apiMasterProgramEducation/MezuniyetBilgiKaydet", model);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<List<MezuniyetBilgi>>();
readTask.Wait();
list = readTask.Result;
model = list.FirstOrDefault();
return Json(new
{
Success = true,
data = model,
Message = SuccessMessage.MEZUNIYET_BILGISI_INSERT_MESSAGE,
JsonRequestBehavior.AllowGet
});
}
}
}
API:
public IHttpActionResult MezuniyetBilgiKaydet(MezuniyetBilgi model)
{
List<MezuniyetBilgi> detay = new List<MezuniyetBilgi>();
try
{
using (var ctx = new ktdbEntities())
{
if (model != null)
{
var query = ctx.mezuniyetBilgisiEkle(model.KullaniciId, model.MezuniyetTarih, model.MezunOlduguOkul,
model.MezunOlduguFakulte, model.MezunOlduguBolum, (float)(model.MezuniyetNotu));
model.Output = true;
detay.Add(model);
return Ok(detay);
}
}
}
catch (Exception e)
{
model.Output = false;
model.Message = e.Message;
detay.Add(model);
}
return Ok(detay);
}

my filtering options doesn't work but in the first page

I've written some ActionLinks to filter the data on a movieshop base on genre while using PagedList.Mvc for paging.
The problem is that the ActionLinks work properly,but only filter the movies existing on the first page. What can I do?
View:
#using PagedList.Mvc
#using Shop.CustomHtmlHelpers
#using Shop.Domain.Entities
#model PagedList.IPagedList<Shop.Domain.Entities.Movie>
#{
ViewBag.Title = "MovieDisplay";
}
<h2>MovieDisplay</h2>
#using (#Html.BeginForm("MovieDisplay", "Movies", FormMethod.Get))
{
<div class="container">
<div class="row">
<div class="col-md-10">
#foreach (Product p in Model)
{
var item = (Movie)p;
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-6">
<div class="tile">
<br />
<b>#item.Title</b>
<br />
#item.Year
<br/>
#item.Genre
<br/>
#item.Director.Name
#Html.Image(#item.Image,"200")
<br />
$ #item.Price
<br/>
<br />
<button onclick="location.href = '#Url.Action("AddtoCart", "ShoppingCart", new {id = p.Id})'" type="button" class="btn btn-success btn-su btn-sm ">
<span> <i class="fa fa-shopping-basket" aria-hidden="true"></i></span> AddtoCart
</button>
<br />
<br /><br />
</div>
</div>
}
</div>
</div>
</div>
}
#Html.ActionLink("Horror", "MovieDisplay", new { Genre = "Horror" } )
#Html.ActionLink("Action", "MovieDisplay", new { Genre = "Action" })
#Html.ActionLink("Drama", "MovieDisplay", new { Genre = "Drama" })
#Html.ActionLink("Animation", "MovieDisplay", new { Genre = "Animation" })
#Html.ActionLink("Comedy", "MovieDisplay", new { Genre = "Comedy" })
#Html.ActionLink("Crime", "MovieDisplay", new { Genre = "Crime" })
#Html.ActionLink("Sci-Fi", "MovieDisplay", new { Genre = "Sci-Fi" })
#Html.ActionLink("Fantasy", "MovieDisplay", new { Genre = "Fantasy" })
#Html.ActionLink("Historical", "MovieDisplay", new { Genre = "Historical" })
#Html.ActionLink("Musical", "MovieDisplay", new { Genre = "Musical" })
#Html.PagedListPager(Model, page => Url.Action("MovieDisplay", new { page, searchTerm = Request.QueryString["searchTerm"], Genre = "Genre" }))
Related ActionResult:
public ActionResult MovieDisplay(string searchTerm, int? page , string genre)
{
MediaContext mc = new MediaContext();
var movies = mc.Movies.ToList().ToPagedList(page ?? 1, 6);
if(genre !=null)
movies = movies.Where(m => m.Genre == genre).ToList().ToPagedList(page ?? 1, 6);
if (string.IsNullOrEmpty(searchTerm))
{ }
else
movies = mc.Movies.Where(x => x.Title.Contains(searchTerm)).ToList().ToPagedList(page ?? 1, 6);
return View(movies);
}
The problem was nothing but a silly mistake I made in the ActionResult :
movies = movies.Where(m => m.Genre == genre).ToList().ToPagedList(page ?? 1, 6);
Here I actually filter the existing movies ! I should have added the whole movies to the list just like I did for the searchTerm (that's why the search worked properly for all the pages)
movies = mc.Movies.Where(m => m.Genre == genre).ToList().ToPagedList(page ?? 1, 6);

MVC data validation for listboxfor not working

I am having a bit of trouble with my form being validated even if my listboxfor is empty. This is the viewmodel im using:
public class CopyExcelReportSearchViewModel: IViewModel
{
[Required]
public DateRange DateRange { get; set; }
[Required]
public Guid CustomerId { get; set; }
[Required]
public List<Guid> ProjectIds { get; set; }
[Required]
public List<Guid> LocationsIds { get; set; }
public List<Customer> AvailableCustomers { get; set; }
public List<Project> AvailableProjects { get; set; }
public List<Location> AvailableLocations { get; set; }
public CopyExcelReportSearchViewModel()
{
ProjectIds = new List<Guid>();
LocationsIds = new List<Guid>();
AvailableCustomers = new List<Customer>();
AvailableProjects = new List<Project>();
AvailableLocations = new List<Location>();
}
}
Here is the html
#model Path.CopyExcelReportSearchViewModel
#{
var customerDropdown = Model.AvailableCustomers.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString(),
Selected = Model.CustomerId == x.Id
});
var locationDropdown = Model.AvailableLocations.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString(),
Selected = Model.LocationsIds.Any(y => y == x.Id)
});
var projectDropdown = Model.AvailableProjects.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString(),
Selected = Model.ProjectIds.Any(y => y == x.Id)
});
}
<script>
var optionTemplate = [
'<option value="[VALUE]">[TEXT]</option>'
].join();
$(function () {
$('#CustomerId').change(function () {
var value = $(this).val();
$.ajax({
url: '#Url.Action("GetProjectsByCustomerId")?customerId=' + value,
datatype: 'json',
type: 'GET',
cache: false,
success: function (data) {
var projectSelect = $('#ProjectIds');
var options = '';
for (var i = 0; i < data.length; i++) {
options += optionTemplate.replace('[VALUE]', data[i].id).replace('[TEXT]', data[i].name);
}
projectSelect.empty().append(options).removeAttr('disabled').trigger('chosen:updated');
}
});
});
$('#CustomerId').trigger('change');
});
</script>
#using (Html.BeginForm("GenerateCopyReportExcel", "Report", FormMethod.Post))
{
//todo - Fix projectids validation
<div id="DlgStockReportSearch" class="modal fade" data-backdrop="static" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>#Language.KPIReport</h3>
</div>
<div class="modal-body clearfix">
<div class="col-xs-12">
<div class="form-group">
<label for="CustomerId">#Language.Customer</label>
#Html.DropDownListFor(x => x.CustomerId, customerDropdown, new { #class = "form-control chosen", placeholder = Language.Customer })
#Html.ValidationMessageFor(x => x.CustomerId)
</div>
<div class="form-group required">
<label for="DateRange">#Language.Date</label>
#Html.EditorFor(x => x.DateRange)
</div>
<div class="form-group">
<label for="ProjectIds">#Language.Projects</label>
<div class="input-group button">
#Html.ListBoxFor(x => x.ProjectIds, projectDropdown, new { #class = "form-control chosen", multiple = ""})
#Html.ValidationMessageFor(m => m.ProjectIds)
<span class="input-group-addon">
<button type="button" class="btn btn-default chosen-select-all">Select all</button>
</span>
</div>
</div>
<div class="form-group">
<label for="LocationsIds">#Language.Location</label>
<div class="input-group button">
#Html.ListBoxFor(x => x.LocationsIds, locationDropdown, new { #class = "form-control chosen", multiple = "" })
<span class="input-group-addon">
<button type="button" class="btn btn-default chosen-select-all">Select all</button>
</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" aria-hidden="true">#Language.Close</button>
<button type="submit" class="btn btn-primary">
#Language.GenerateReport
</button>
</div>
</div>
</div>
</div>
}
For some reason, I am able to submit the form even if i leave the listboxfor for projects and locations empty.

Unable to use telerik notification in asp.net mvc project

I would like to use noty in my Asp.net Mvc project, however since I can not do it, I prefer telerik aversely. The algorithm is, user registers a web page,processes at the server side, in case of success I would like to show a message at the client. Here is the usage of telerik notification:
http://demos.telerik.com/aspnet-mvc/notification/index
here is my source: (HomeController/Register)
[HttpPost]
public ActionResult Register(Users user)
{
IAraclar tool = null;
string uname = null;
IKisiBL userBusinessRule = null;
try
{
tool = new toollar();
uname = tool.GetUserName(user.UserEmail);
user.UserName = uname;
USERS newDataUser = new USERS
{
USER_ID = 0,
USER_EMAIL = user.UserEmail,
USER_NAME = user.UserName,
USER_PASSWORD = user.UserPassword,
USER_ROLE_TIP = (short)user.UserRoleTipi,
USER_KURUM_TIPI = (short)user.UserKurumTipi
};
using (LojmanEntities entities = new LojmanEntities())
{
entities.USERS.Add(newDataUser);
entities.SaveChanges();
}
}
catch (Exception ex)
{
tool.HataRaporla(ex);
throw;
}
//ViewData["SuccessMessage"] = SistemMesajlari.KayitTamamlandi_ok();
return View();
}
https://docs.google.com/document/d/11EoaOQysDa0FmNIawSZ1AafOh0pZ58W_Qku2Z3BnXWo/edit?usp=sharing
Here is my Register.cshtml, in which tightly coupled with the Action above :
#model LojmanMVC.Domain.Entities.Users
#{
ViewBag.Title = "Lojman Bilgi Sistemi Kullanıcı Kaydı";
}
<h2>Lojman Bilgi Sistemi Kullanıcı Kaydı</h2>
<p id="sifresonuc"> </p>
#*prospective item that shows message*#
#(Html.Kendo().Notification()
.Name("staticNotification")
.AppendTo("#appendto")
)
#*classical form in mvc*#
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Lütfen kullanıcı bilgilerinizi giriniz: </legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserEmail) (Bakanlıkça verilen e-posta adresiniz)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserEmail)
#Html.ValidationMessageFor(model => model.UserEmail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserPassword)
</div>
<div class="editor-field">
#Html.TextBoxFor(item => item.UserPassword, new { id = "password1" })
</div>
<div class="editor-label">
<label for="male">Lütfen şifrenizi tekrar giriniz: </label>
</div>
<div class="editor-field">
<input type="password" name="password2" id="password2" />
</div>
<div class="editor-label">
<label for="male">Lütfen rolünüzü giriniz: </label>
</div>
<div class="editor-field">
#Html.MyEnumDropDownListFor(m => m.UserRoleTipi)
</div>
<p>
<input type="submit" id="registerButton" value="Kayıt Ol" />
</p>
<button id="showStaticNotification" class="k-button">Static in the panel below</button>
</fieldset>
}
<script type="text/javascript">
console.log("1");
function checkPasswordMatch() {
console.log("checkPasswordMatch");
var password = $("#password1").val();
var confirmPassword = $("#password2").val();
if (password != confirmPassword) {
$("#sifresonuc").html("Şifreler uyuşmamaktadır!");
var $p = $("#sifresonuc");
var $button = $("#registerButton");
$button.prop('disabled', true);
$p.css("background-color", "red").show(500);
}
else {
$("#sifresonuc").html("");
var $p = $("#sifresonuc");
$p.css("background-color", "white").show(500);
var $button = $("#registerButton");
$button.prop('disabled', false);
}
}
console.log("2");
$(document).ready(function () {
$("#password2").keyup(checkPasswordMatch);
});
console.log("3");
function InputToLower(obj) {
if (obj.value != "") {
obj.value = obj.value.replace('İ', 'i').replace('I', 'ı').toLowerCase();
}
}
console.log("4");
$(function () {
$("#registerButton").click(function (e) {
console.log("5");
// e.preventDefault();
var errorSummary = $('.validation-summary-errors');
console.log("6");
if (errorSummary.length == 0) {
$('#listError').remove();
$('<div class="validation-summary-errors"></div>').insertAfter($('.validation-summary-valid'));
$(".validation-summary-errors").append("<ul id='listError'><li>0 karakter giremezsiniz. OSI-122 </li></ul>");
}
else if (errorSummary.length == 1) {
$('#listError').remove();
$(".validation-summary-errors").append("<ul id='listError'><li>You cannot enter more than 20 characters.</li></ul>");
}
//return false;
// place that sets notification
console.log("7");
var d = new Date();
staticNotification.show(kendo.toString(d, 'HH:MM:ss.') + kendo.toString(d.getMilliseconds(), "000"), "info");
var container = $(staticNotification.options.appendTo);
container.scrollTop(container[0].scrollHeight);
console.log("8");
});
});
</script>
https://docs.google.com/document/d/1t7g9K4v5BrIyFkHVCMxVowDUbMlT3P6Tsz-88d7YOuA/edit?usp=sharing
(Since I can not write these lines of code despite every efforts, I share it via google docs)
When I run the code, there is no notification appear in the page, and "1,2,3,4" was appeared at the console.Function contains 5 does not work there. What things did I do wrong?
Thanks in advance.
I think you should try to assign the handler of your registerButton in the $document.ready() function, and try to assign the handler of the click event using the functions unbind/bind.
document.ready(function(){
$("#registerButton").unbind("click").bind("click", function() {
<your code here>
...
});
});

Resources