How to do Jquery ajax post to controller mvc - asp.net-mvc-3

I just can't figure out what I am not doing right,From a viewmodel,I try to grab from user {**Tousername and messagebody},#ToUserName** is correctly sent while #Body is null in controller when I debug .I have the following Jquery code:
$("#SendMessage").click(function () {
var message = GrabMessage();
var jsonData = JSON.stringify(message, null, 2);
$.ajax({
url: '#Url.Content("~/Message/Compose/")',
type: 'POST',
data: jsonData,
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
$('#default_message').append("message sent ");
switchToSentMessagesTab();
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
return false;
});
function switchToSentMessagesTab() {
$('a[href="#default_message"]').click();
}
function GrabMessage() {
var touser = $("#ToUserName").val();
var text = $("#Body").val();
var result =
{
Body: text,
ToUserName: touser
};
return result;
}
});
And the razer View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.ToUserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ToUserName, new { #class ="autocomplete"})
#Html.ValidationMessageFor(model => model.ToUserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Body)
#Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input id="SendMessage" type="submit" value="Send" />
</p>
}
and controller Action:
[HttpPost]
public ActionResult Compose(PrivateMessageViewModel m)
{
if (User.Identity.IsAuthenticated )
{
if (ModelState.IsValid)
{
var ToUserName = users.Profiles.First(x => x.UserName == m.ToUserName);
PrivateMessage message = new PrivateMessage
{
//do some stuff here:
};
db.SendMessage(message);
return RedirectToAction(//Some view here...)
}
}
return PartialView(m);
}

Related

MVC Controller receiving null values from ajax

I'm trying to send an Ajax post to mvc controller contains two parameters.
First parameter: serialized model (Folder)
Second parameter: Array (Periods)
The problem is the controller received null values in the first parameter:
Javascript code :
var data = JSON.stringify({
Folder: $('#Folder').serialize(),
Periods: periodsArr
});
function save(data) {
return $.ajax({
type: 'POST',
//cache: false,
contentType: 'application/json', //Without folder not empty and period is empty
//traditional: true,
//dataType: "json",
url: '#Url.Action("AddOrEditFolder", "Folder")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!" + Error);
}
});
}
Html code:
<div class="card-body">
#using (Html.BeginForm(null, null, new { #id = string.Empty }, FormMethod.Post, new { #id = "Folder" }))
{
#Html.HiddenFor(model => model.FolderID)
<div class="row">
<label for="FirstNameAR" class="col-sm-2 control-label">الإسم الشخصي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameAR, new { htmlAttributes = new { #id= "FirstNameAr", #class = "form-control" } })
</div>
<label for="FirstNameFR" class="col-sm-2 control-label">الإسم العائلي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameFR, new { htmlAttributes = new { #id = "FirstNameFr", #class = "form-control" } })
</div>
</div> <br />
Controller code:
[HttpPost]
//[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrEditFolder(Folder Folder, Period[] Periods)
{
//Folder Folder = JsonConvert.DeserializeObject<Folder>(Obj);
using (InternshipsEntities dbContext = new InternshipsEntities())
{
//Some code here
}
}
How can I solve that problem ?
Use below code to create data object to pass in Ajax request.
var Folder = { };
$.each($('#Folder').serializeArray(), function() {
Folder[this.name] = this.value;
});
var data = {
Folder: Folder
Periods: periodsArr
};

Partial View not printing values in mvc 5

I'm using ajax call to execute partial view controller action to print max batch number. Everything executes, but the value doesn't print in partial view. On selected dropdown list I'm calling ajax method to execute. Below is my code that i'm using.
Models.Batch.cs
[Required]
[StringLength(100)]
[DataType(DataType.Text)]
[Display(Name = "Batch Number")]
public string BatchNumber { get; set; }
BatchController.cs
public PartialViewResult GetBatchNumber(string CourseID)
{
Context.Batches contBatch = new Context.Batches();
Models.Batches b = new Models.Batches();
b.BatchNumber = contBatch.GetallBatchList().ToList().Where(p => p.CourseId == CourseID).Select(p => p.BatchNumber).Max().FirstOrDefault().ToString();
ViewBag.Message = b.BatchNumber;
return PartialView(b);
}
CreateBatch.cshtml
<div class="col-md-10">
#Html.DropDownListFor(m => m.CourseId, Model.Courses, new { id = "ddlCourse" })
<div id="partialDiv">
#{
Html.RenderPartial("GetBatchNumber", Model);
}
</div>
<script>
$("#ddlCourse").on('change', function () {
var selValue = $('#ddlCourse').val();
$.ajax({
type: "GET",
url: '/Batch/GetBatchNumber?CourseId=' + selValue,
dataType: "json",
data: "",
success: function (data) {
$("#partialDiv").html(data);
},
failure: function (data) {
alert('oops something went wrong');
}
});
});
</script>
</div>
GetBatchNumber.cshtml
#model WebApplication1.Models.Batches
<div class="form-group">
#Html.LabelFor(model => model.BatchNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.BatchNumber)
#Html.ValidationMessageFor(model => model.BatchNumber, "", new { #class = "text-danger" })
</div>
</div>

How to use ajax to post Kendo upload files to controller

When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});
For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}

MVC3 TextBoxFor date is in American format. Want UK format

In my model I am using two date properties, start date and end date. I have mapped these two properties to two TextBoxFor textboxes. When the page loads these two dates are in American format but I want it to be UK format.
#model UserManager.Models.vw_Group_Model
#{
ViewBag.Title = "Edit Group";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div id="edit-user" style="padding:25px;">
<fieldset>
<legend>Edit group details</legend>
#* <div class="editor-label">
#Html.LabelFor(model => model.companyId)
</div>*#
#* <div class="editor-field">
#Html.EditorFor(model => model.companyId) - Non editable
#Html.ValidationMessageFor(model => model.companyId)
</div>*#
<div class="editor-label">
#Html.LabelFor(model => model.RowType)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.RowType, new { #readonly = "readonly" }) - Non editable
#Html.ValidationMessageFor(model => model.RowType)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.groupName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.groupName)
#Html.ValidationMessageFor(model => model.groupName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.companyName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.companyName) - Non editable
#Html.ValidationMessageFor(model => model.companyName)
</div>
#* <div id="hiddenSelection">
#Html.HiddenFor(model => model.selected_company, new { id = "hdnCompany" })
#Html.HiddenFor(model => model.selected_group, new { id = "hdnGroup" })
</div>*#
#*<fieldset style="width: 400px; padding-left: 15px;">
<legend>New company</legend>
<div id="createuser-companysearch">
#{Html.RenderAction("_txtAutocompleteCompanySearch", "GroupManager");}
</div>
</fieldset>*#
#* <fieldset style="width: 400px; padding-left: 15px;">
<legend>New group</legend>
<div id="createuser-groupsearch">
#{Html.RenderAction("_txtGroupSearchForm", "GroupManager");}
</div>
</fieldset>*#
<div class="editor-label">
#Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EndDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EndDate)
#Html.ValidationMessageFor(model => model.EndDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsActive)
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.IsActive)
#Html.ValidationMessageFor(model => model.IsActive)
</div>
<p>
<input type="submit" value="Edit" />
</p>
#Html.ValidationSummary()
<br />
#Html.ActionLink("Back to Group Manager Dashboard", "Index")
</fieldset>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
// chkSelection();
// Non editable fields grey
$("#oldCompanyName").css("background-color", "gray");
$("#oldGroupName").css("background-color", "gray");
$("#RowType").css("background-color", "gray");
// Assume group name already exists based on it being a value loaded from model
var valueCompany = $("#oldCompanyName").val();
// $("#hdnCompany").val(valueCompany);
$('#selected_company').val(valueCompany);
var valueGroup = $("#oldGroupName").val();
// $("#hdnGroup").val(valueGroup);
// $('#groupName').val(valueGroup);
$('#txtGroupnameExistsAlf').css("background-color", "#33ff00").val('ALF group does exist');
$('#txtGroupnameExistsBrad').css("background-color", "#33ff00").val('BRAD group does exist');
var rowType = $('#RowType').val();
if (rowType == "ALF") {
var company = $('#companyName').val();
$("#company_name").val(company);
$('#txtCompanynameExistsAlf').css("background-color", "#F7D358").val('Company does exist');
}
else {
var company = $('#companyName').val();
$("#company_name").val(company);
$('#txtCompanynameExistsBrad').css("background-color", "#F7D358").val('Company does exist');
}
});
</script>
#*
$("#groupName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("LookUpGroupName", "UserManager")',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
value: request.term
},
success: function (data) {
response($.map(data, function (item) {
// alert(item.group);
return {
label: item.group,
value: item.group
} // end of return
})); // end of response
}, // end of success
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} // end of error
}); // end of ajax
},
minLength: 2,
select: function (event, ui) { // Assign to hidden values to trigger onchange ajax call.
$.ajax({
url: '#Url.Action("GroupnameCheck", "UserManager")',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
value: ui.item.label
},
success: function (data) {
$.each(data, function (index, value) {
if (index == "AlfGroup") {
$("#txtGroupnameExistsAlf").val(value);
if ($("#txtGroupnameExistsAlf").val() == "Alf Group doesn't exist.") {
$("#txtGroupnameExistsAlf").css("background-color", "red");
}
else {
$('#txtGroupnameExistsAlf').css("background-color", "#33ff00");
}
}
if (index == "BradGroup") {
$("#txtGroupnameExistsBrad").val(value);
if ($("#txtGroupnameExistsBrad").val() == "Brad Group doesn't exist.") {
$("#txtGroupnameExistsBrad").css("background-color", "red");
}
else {
$('#txtGroupnameExistsBrad').css("background-color", "#33ff00");
}
}
var selectedVal = $("#groupName").val();
$('#hdnGroup').val(selectedVal);
});
}, // end of success
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} // end of error
}); // end of ajax
$('#hdnGroupAlf').val(ui.item.label);
$('#hdnGroupBrad').val(ui.item.label);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
$("#selected_company").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("LookUpCompanyName", "GroupManager")',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
value: request.term + ":" + $('#RowType').val()
},
success: function (data) {
response($.map(data, function (item) {
// alert(item.group);
return {
label: item.group,
value: item.group
} // end of return
})); // end of response
}, // end of success
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} // end of error
}); // end of ajax
},
minLength: 2,
select: function (event, ui) { // Assign to hidden values to trigger onchange ajax call.
$('#hdnCompany').val(ui.item.label);
}
});
function chkSelection() {
if($('#RowType').text() == "ALF") {
$('#companyname-checker-brad').hide();
$('#groupname-checker-brad').hide();
}
else {
$('#companyname-checker-alf').hide();
$('#groupname-checker-alf').hide();
}
}*#
Model
[Required(ErrorMessage = "Start Date is a required field")]
//[Display(Name = "Start Date")]
//[DataType(DataType.Date)]
//[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[Required(ErrorMessage = "End Date is a required field")]
//[Display(Name = "End Date")]
//[DataType(DataType.Date)]
//[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
Currently the date is displayed on the page as this:
01/01/0001
Anyone know how to change this? Preferably a quick fix. Thanks.
I ended up writing this javascript to split the date string and then rearrange it to how I want it.
function dateFormater() {
var date = $('#StartDate').val()
var arrDate = date.split("/");
$('#StartDate').val(arrDate[1] + "/" + arrDate[0] + "/" + arrDate[2]);
date, arrDate = null;
date = $('#EndDate').val()
arrDate = date.split("/");
$('#EndDate').val(arrDate[1] + "/" + arrDate[0] + "/" + arrDate[2]);
};

Reset tinyMCE box after submit

i have the follow MVC View
#model Site.SupportItems.SiteAditionalInformation
#using Site.Helpers.Extenders;
#{
Response.CacheControl = "no-cache";
}
<div>
#using (Html.BeginForm("SaveSiteAdditionalInformation", "Support", FormMethod.Post, new { #Id = "frmSiteInformation" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Site Aditional Information</legend>
<div class="site-PO-footer-outline-left-comment">
<div class="site-item-outline">
<div class="site-label-left ui-corner-all">
#Html.LabelFor(model => model.Office)
</div>
<div class="site-detail">
#Html.DropDownListFor(x => x.Office, Model.Offices.ToSelectList("ValueSelected", "DisplayValueSelected", Model.Office))
#Html.ValidationMessageFor(model => model.Office)
</div>
</div>
<div class="site-item-outline">
<div class="site-label-left ui-corner-all">
#Html.LabelFor(model => model.AdditionalInformation)
</div>
<div class="site-detail">
#Html.TextAreaFor(model => model.AdditionalInformation, new { #Class = "ui-site-rtb" })
#Html.ValidationMessageFor(model => model.AdditionalInformation)
</div>
</div>
</div>
<p>
<input type="submit" value="Save" id="btnSubmit" />
</p>
</fieldset>
}
<script type="text/javascript">
$(function ()
{
var thisTab = $(Globals.ActiveTabId());
var previousSelectedOffice;
$('#Office', thisTab).click(function ()
{
previousSelectedOffice = $('#Office', thisTab).val();
}).change(function (e)
{
var setNewContent = function ()
{
$('#loading-Panel').Loading('show');
$.ajax('#Url.Action("GetSiteSpecificText")', {
data: { Office: $('#Office', thisTab).val(),
rnd: Math.random() * 10000
},
cached: false,
success: function (response)
{
if (response != null)
{
$('#AdditionalInformation', thisTab).html(response);
}
else
$('#AdditionalInformation', thisTab).html('');
$('#loading-Panel').Loading('hide');
}
});
};
if (tinyMCE.activeEditor.isDirty())
{
$('<div/>').text('The Text has changed for the Additional Information. Would you like to save?').dialog({
title: 'Text has Changed',
buttons: {
'Ok': function ()
{
$('#loading-Panel').Loading('show');
var beforeSave = $('#Office', thisTab).val();
$('#Office', thisTab).val(previousSelectedOffice);
$('#frmSiteInformation', thisTab).trigger('submit');
$('#Office', thisTab).val(beforeSave);
setNewContent();
$(this).dialog('close');
},
'Cancel': function ()
{
$(this).dialog('close');
$('#Office', thisTab).val(previousSelectedOffice);
}
}
});
}
else
{
setNewContent();
}
});
$('#frmSiteInformation', thisTab).submit(function ()
{
tinyMCE.triggerSave();
var data = $('#frmSiteInformation', thisTab).serializeObject();
$('#loading-Panel').Loading('show');
$.ajax($(this).attr('action'), {
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (data)
{
if (data.SaveResult)
$('<div/>').text('Save Successful for' + $('#Office option:selected', thisTab).text())
.dialog({
title: 'Save Successful',
buttons: {
'Ok': function ()
{
$(this).dialog('close');
}
}
});
$('#loading-Panel').Loading('hide');
}
});
return false;
});
});
</script>
</div>
and while most of it is doing what i expect if i change the dropdown i want to clear the RTB back to nothing (or the response value if there is one from the DB)
while this is working if i change the dropdown again the tinyMCE.activeEditor.isDirty() is always coming back as true when i believe it should be false.
i have tried tinymce.execCommand('mceToggleEditor',false,'AdditionalInformation');
but this only reloads the first RTB
and also tinymce.execCommand('mceRemoveEditor',false,'AdditionalInformation');
which causes an error.
if anyone could point me in the right direction i would really appreciate it.
thanks.
Edit I have solved the problem i am having using the mceRemoveEditor command
the function call for setNewContent is as follows
var setNewContent = function ()
{
$('#loading-Panel').Loading('show');
$.ajax('#Url.Action("GetSiteSpecificText")', {
data: { Office: $('#Office', thisTab).val(),
rnd: Math.random() * 10000
},
cached: false,
success: function (response)
{
tinymce.execCommand('mceRemoveEditor', false, 'AdditionalInformation');
if (response != null)
{
$('#AdditionalInformation', thisTab).html(response);
}
else
$('#AdditionalInformation', thisTab).html('');
tinymce.execCommand('mceAddControl', false, 'AdditionalInformation');
$('#loading-Panel').Loading('hide');
}
});
};
Thanks for the help.

Resources