How to get input data from MVC ViewModel into ajax post - ajax

I am fetching data from a SQL database table into an ASP.NET MVC Razor view but I have troubles getting changed input data into an Ajax post such as:
#model MyViewModel
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
var postData = #Html.Raw(Json.Encode(#Model));
//alert(postData.Test);
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}
When I load the view everything is displayed correctly. The controller action is triggered correctly and the Id (which can not be altered) is passed properly too. However when input fields are changed not the changed values get passed to the controller but the original values that were fetched into the view.
The serialization seems to work, since the alert (postData.Test) returns a value - but always the unchanged one.
Any help would be appreciated.

var postData = #Html.Raw(Json.Encode(#Model));
This line is the culprit. When Razor renders the script, it will assign the original/unchanged model to your postData variable.
If you use "Inspect Element" or dev tools to check the value of postData, you'll see that the values won't change because they're statically assigned.
You need to check for the new values every time you click the button by using
var postData = $("form").serialize();
And be sure to wrap your input fields inside a form tag. See code below:
<form>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
</form>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
// use form.serialize or use the id/class of your form
var postData = $("form").serialize();
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}

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

Pass multiple Id's against multiple values in database

I'm working on a task that uses autocomplete textbox items containing names, stores in textbox or in listbox with their associated Id's(hidden) and inserted into the required table (only their related id's). I'm working on mvc 5 application. So far I've achieved to add value in listbox with names but not Id's. And trying to add the listbox values get stored in database. Below is my code.
Note:- I'm using partial view to display listbox when the button clicks. The current scenario is that it the listbox overwrites the first value when inserting second value.
StudentBatch.cs
public List<string> selectedids { get; set; }
public List<string> SelectedNames { get; set; }
Create.cshtml
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
<input type="button" value="Add Text" id="addtypevalue" />
<div id="typevaluelist"></div>
</div>
</div>
<div id="new" style="display:none;">
<div class="typevalue">
<input type="text" name="typevalue" />
<button type="button" class="delete">Delete</button>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add Students" class="btn btn-default" />
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/CreateStudent",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.FirstName, value: item.FirstName };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
<script>
$('#addtypevalue').click(function () {
$(document).ready(function () {
var selValue = $('#StudentName').val();
$.ajax({
type: "GET",
url: '#Url.Action("GetListBox", "Student")',
dataType: "html",
data: { CourseId: selValue },
success: function (data) {
$("#partialDiv").html(data);
},
failure: function (data) {
alert('oops something went wrong');
}
});
});
});
</script>
GetListBox.cshtml
#model WebApplication1.Models.StudentBatch
#if (ViewBag.Value != null)
{
#Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.SelectedNames))
}
StudentController.cs
public PartialViewResult GetListBox(string CourseID)
{
Context.Student studCont = new Context.Student();
Models.StudentBatch student = new Models.StudentBatch();
student.SelectedNames = new List<string>();
student.SelectedNames.Add(CourseID);
ViewBag.Value = student;
return PartialView(student);
}

Form post from partial view to API

I am trying to create an SPA application using Sammy. When I call #/entitycreate link, I return a partial view from Home controller which contains an html form to submit. Partial view comes as I expect but rest of it doesn't work. Below are my problems and questions, I'd appreciate for any help.
KO binding doesn't work in partial view, even though I did exactly how it's done in the default SPA project template (see home.viewmodel.js).
This one is the most critical: when I submit this form to my API with ajax/post, my model always comes back with a null value, therefore I can't create an entity via my API. I have tried with [FromBody] and without, model always comes null.
In some sense a general question, should I include Html.AntiForgeryToken() in my form and [ValidateAntiForgeryToken] attribute in my API action?
Partial View:
#model namespace.SectorViewModel
<!-- ko with: sectorcreate -->
<div class="six wide column">
<div class="ui segments">
<div class="ui segment">
<h4 class="ui center aligned header">Create New Sector</h4>
</div>
<div class="ui secondary segment">
<form id="entity-create-form" class="ui form" action="#/sectorcreatepost" method="post" data-bind="submit: createEntity">
<!-- I am not sure if I should include AntiForgeryToken for WebAPI call -->
<!-- Html.AntiForgeryToken() -->
<fieldset>
<div class="field required">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { data_bind = "value: name" })
</div>
<div class="ui two buttons">
<button class="ui positive button" type="submit">Create</button>
<button class="ui button" type="button" id="operation-cancel">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!-- /ko -->
JS View Model:
function SectorCreateViewModel(app, dataModel) {
var self = this;
self.name = ko.observable("ko binding doesn't work");
self.createEntity = function () {
console.log("ko binding doesn't work");
}
Sammy(function () {
this.get("#sectorcreateget", function () {
$.ajax({
url: "/home/getview",
type: "get",
data: { viewName: "sectorcreate" },
success: function (view) {
$("#main").html(view);
}
});
return false;
});
this.post("#/sectorcreatepost",
function () {
$.ajax({
url: "/api/sectors",
type: "post",
data: $("#entity-create-form").serialize(),
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
}
});
return false;
});
this.get("#/yeni-sektor", function () {
this.app.runRoute("get", "#sectorcreateget");
});
});
return self;
}
app.addViewModel({
name: "SectorCreate",
bindingMemberName: "sectorcreate",
factory: SectorCreateViewModel
});
API Action:
public HttpResponseMessage Post([FromBody]SectorViewModel model)
{
// model is always null, with or without [FromBody]
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest);
// repository operations...
return response;
}
I have removed contentType: "application/json; charset=utf-8", from ajax request based on the article here. #2 is now resolved, #1 and #3 still remains to be answered.

passing datetime value from the view to controller using ajax call

I am using timepicki (one of the jquery timepickers) to pass DateTime value in the view to the controller, especially to the ActionResult Create method. I have tested under Sources tab using F12 for ajax call written in javascript in the view, and in fact, the value is successfully stored in the variable inside of the function, but doesn't seem to be passing its value to the controller. Can you guys help me why it is not passing its value to the controller? Any help is appreciated.
View:
#model test.Models.Employee
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.MondayId, "Monday: ", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
Start: <input type="text" name="timepicker" class="time_element" id="monStart"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" id="submit" onclick=""/>
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/timepicki.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/timepicki.css")" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function(){
$(".time_element").timepicki();
});
</script>
<script type="text/javascript">
$("#submit").click(function () {
var monStart = $('#monStart').val();
$.ajax({
url: '#Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart },
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
})
});
</script>
}
controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee employee, DateTime? monStart)
{
//codes
}
You are just missing the AntiForgeryToken on your ajax call. So your call:
$.ajax({
url: '#Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart},
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
Should be:
var myToken = $('[name=__RequestVerificationToken]').val();
$.ajax({
url: '#Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart, __RequestVerificationToken : myToken },
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});

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