Ajax begin form db record with mvc - asp.net-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);
}

Related

Ajax.BeginForm triggers OnFailure with no reason

I got stucked with (it seems to be) a simple problem.
My goal is to create a modal with an Ajax form. A child action gets the modal in a partial view, and when edited, submit button posts Ajax form which returns just Json data. Built-in code in Ajax.BeginForm should trigger OnSuccess or OnFailure depending on the result of the action.
The problem is OnFailure is triggered and OnSuccess don't, although the action finishes OK, and post return a 200 code. The "data" param in OnFailure function contains the HTML of the whole page.
This is the code:
(1) Snippet to load the modal in the main view:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
#Html.Action("GetDialogV2", "Fianzas", new { idArrendamiento = Model.Id_Arrendamiento })
</div>
(2) Button to open the modal in the main view:
<button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#exampleModal">
<i class="far fa-hand-holding-usd"></i> Modal
</button>
(3) The partial view with the modal (and the Ajax Form), GetDialogV2.cshtml:
#model EditFianzas_vm
#{
AjaxOptions ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "Respuesta",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
};
}
#using (Ajax.BeginForm(ajaxOptions))
{
#Html.AntiForgeryToken()
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Fianza</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id_Arrendamiento)
<div class="form-group">
#Html.LabelFor(model => model.Importe, new { #class = "control-label col-md-6" })
<div class="col-md-8">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-euro-sign"></i></span>
</div>
#Html.EditorFor(model => model.Importe, new { htmlAttributes = new { #class = "form-control importe" } })
</div>
#Html.ValidationMessageFor(model => model.Importe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fecha_Abono, new { #class = "control-label col-md-6" })
<div class="col-md-8">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar"></i></span>
</div>
#Html.TextBoxFor(model => model.Fecha_Abono, "{0:dd/MM/yyyy}", new { #class = "form-control datepicker" })
</div>
#Html.ValidationMessageFor(model => model.Fecha_Abono, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-8">
<input type="text" id="Respuesta" class="form-control" />
</div>
</div>
</div>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary" id="botonPrueba">Guardar</button>
</div>
</div>
<!-- /.modal-content -->
</div>
}
(4) The Javascript in the main view:
#section scripts
{
<script type="text/javascript">
function OnSuccess(data) {
if (data.Success == true) {
toastr.success("Operación realizada.", "Fianzas");
$("#exampleModal").modal('hide');
}
else {
if (data.modelState) {
$.each(d.modelState, function (i, item) {
toastr.info(i + ': ' + item, "i: item");
//item.valid(); //run jQuery validation to display error
$('#' + i).valid();
});
}
else {
toastr.error(data.Error, "Fianzas");
}
}
}
function OnFailure(data) {
alert(data);
alert('HTTP Status Code: ' + data.param1 + ' Error Message: ' + data.param2);
toastr.error("Se ha producido un error no controlado al realizar la operación.", "Fianzas");
toastr.warning(data, "Fianzas");
}
</script>
}
(5) And finally, the controller:
#region Ajax Form (GetDialogV2)
public PartialViewResult GetDialogV2(int idArrendamiento)
{
//Obtengo el modelo...
Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(idArrendamiento);
//Creo la vista-modelo...
EditFianzas_vm vm = new EditFianzas_vm {
Id_Arrendamiento = idArrendamiento,
Importe = fianza.Importe,
Fecha_Abono = fianza.Fecha_Abono
};
return PartialView(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult GetDialogV2(EditFianzas_vm vm)
{
try
{
if (!ModelState.IsValid)
{
var modelState = ModelState.ToDictionary
(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
modelState.Add("hdId_Arrendamiento", modelState["vm.Id_Arrendamiento"]);
modelState.Remove("vm.Id_Arrendamiento");
modelState.Add("txtImporte", modelState["vm.Importe"]);
modelState.Remove("vm.Importe");
modelState.Add("txtFecha_Abono", modelState["vm.Fecha_Abono"]);
modelState.Remove("vm.Fecha_Abono");
return Json(new { modelState }, JsonRequestBehavior.AllowGet);
//throw (new Exception("Error en la validación del modelo."));
}
//Miro a ver si existen datos para este arrendamiento (no sé si es un edit o un new, si quiero hacerlo todo en una misma acción)
Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(vm.Id_Arrendamiento);
//Compruebo si es nuevo o editado...
if (fianza == null)
{
//Nuevo registro...
fianza = new Arrendamientos_Fianzas
{
Id_Arrendamiento = vm.Id_Arrendamiento,
Importe = vm.Importe,
Fecha_Abono = vm.Fecha_Abono
};
//Actualizo info de control...
fianza.C_Fecha = DateTime.Now;
fianza.C_IdUsuario = Usuario.NombreUsuario;
fianza.C_Comentarios = "Alta de la fianza.";
//Guardo registro...
db.Arrendamientos_Fianzas.Add(fianza);
}
else
{
//Estoy editando, grabo valores...
fianza.Importe = vm.Importe;
fianza.Fecha_Abono = vm.Fecha_Abono;
//Actualizo info de control...
fianza.C_Fecha = DateTime.Now;
fianza.C_IdUsuario = Usuario.NombreUsuario;
fianza.C_Comentarios = "Modificación de los datos de la fianza.";
//Modifico estado del registro en el modelo...
db.Entry(fianza).State = EntityState.Modified;
}
//Guardo cambios...
db.SaveChanges();
//Return...
return new JsonResult() { Data = Json(new { Success = true }) };
}
catch (Exception ex)
{
return new JsonResult() { Data = Json(new { Success = false, Error = ex.Message }) };
}
}
#endregion
Thanks a lot in advance for your time and help.
Best regards,
Fernando.
I got it. It was a subtle solution, as I barely guessed:
If Javascript is disabled, or in certain circumstances, you need to explicitly pass action to the AjaxOptions, like that:
AjaxOptions ajaxOptions = new AjaxOptions()
{
HttpMethod = "POST",
OnSuccess = "OnSuccess(data)",
OnFailure = "OnFailure",
OnBegin = "OnBegin",
OnComplete = "OnComplete",
Url = Url.Action("GetDialogV2")
};

Replacing parent view with partial view from another partial view

This My Parent View In this i am calling partialview(_CityList.cshtml).
#model MedicalOrbit.City
#{
ViewBag.Title = "CreateCity";
}
<h2>Add City</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="Maindiv" class="col-lg-7">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>City Details</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="ibox-content">
<div class="row">
<div class="col-sm-6 b-r">
#*<hr />*#
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label>City Name:</label>
#*#Html.LabelFor(model => model.CityName, htmlAttributes: new { #class = "control-label col-md-2" })*#
<br>
<div >
#Html.EditorFor(model => model.CityName, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter City" } })
#Html.ValidationMessageFor(model => model.CityName, "", new { #class = "text-danger" })
</div>
</div>
<br>
<div>
<input type="submit" value="Create" class="btn btn-w-m btn-primary" />
<input type="submit" value="Cancel" class="btn btn-w-m btn-success" />
</div>
</div>
<div>
<div id="CityList" class="col-sm-6">
#*#Html.Partial("_CityList");*#
#Html.Action("CityList", "City")
</div>
</div>
</div>
</div>
</div>
</div>
}
<div id="Editdiv">
#Html.Action("EditCity", "City")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Partial View(_CityList.cshtml)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CityName)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CityName)
</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = item.CityID })*#
#Ajax.ActionLink("Edit City", "EditCity", "City", new AjaxOptions()
{
UpdateTargetId = "Maindiv",
InsertionMode = InsertionMode.ReplaceWith
})|
#Html.ActionLink("Details", "Details", new { id = item.CityID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.CityID }) |
#Html.ActionLink("Area", "Area", new { #class = "btn btn-warning btn-circle btn-lg fa fa-times", id = item.CityID })
</td>
</tr>
}
</table>
following is my Controller Code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MedicalOrbit.Controllers
{
public class CityController : Controller
{
MediOrbitDatabaseEntities db = new MediOrbitDatabaseEntities();
// GET: City
public ActionResult Index()
{
return View();
}
public ActionResult CityList()
{
return PartialView("_CityList", db.Cities.Where(x => x.status == false).ToList());
}
public ActionResult CreateCity()
{
return View();
}
// POST: City/CreateCity
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateCity(City city)
{
// TODO: Add insert logic here
if (ModelState.IsValid)
{
city.Users = "ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Cities.Add(city);
db.SaveChanges();
return RedirectToAction("CreateCity");
}
return View(city);
}
public ActionResult EditCity(int? id)
{
City city = db.Cities.Where(x => x.CityID == id).FirstOrDefault();
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// POST: /Admin/City/Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditCity(City city)
{
if (ModelState.IsValid)
{
city.Users = "Ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Entry(city).State = EntityState.Modified;
db.SaveChanges();
RedirectToAction("CreateCity");
}
return PartialView("_EditCity",city);
}
}
}
Now what i want is in _CityList.cshtml partial view when user clicks the edit actionlink then main parent view should be replace with another partial view(_EditCity.cshmtl).how i can achieve this.i m not experience in mvc so plz help me.
I am showing you how to do partial views. Hopefully, you will have enough take away to utilize partial views within partial views, if you want.
There might be extra code to help you.
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid4</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$('#LOCATION_NUMBER').click(function () {
var store = $('#storeNbr').val();
this.href = this.href.split("?")[0];
this.href = this.href + '?LOCATION_NUMBER=' + encodeURIComponent(store);
});
})
</script>
</head>
<body>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">My Modal</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<label class="btnIEFix">You can also, Click in Grey Area Outside Modal To Close</label>
<button title="You can also, Click in Grey Area Outside Modal To Close" type="button" class="btn btn-secondary bootBtnMargin" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#Html.HiddenFor(r => r.storeNbr, new { id = "storeNbr" })
#*https://stackoverflow.com/questions/5838273/actionlink-routevalue-from-a-textbox*#
#Ajax.ActionLink(
"Trigger Ajax",
"ReleaseVersion",
null,
new AjaxOptions
{
UpdateTargetId = "result",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
},
new
{
id = "LOCATION_NUMBER"})
<div id="result"></div>
</body>
</html>
Controller:
public class HomeController : Controller
{
public PartialViewResult ReleaseVersion(string LOCATION_NUMBER = "")
{
return PartialView("_ReleaseVersion"); //, model
}
public ActionResult IndexValid4()
{
var storeViewModel = new StoreViewModel { storeNbr = 5 };
return View(storeViewModel);
}
_ReleaseVersion partial view in shared folder:
release version partial view

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>
...
});
});

Postback Contains No Model Data

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?

Resources