How to pass in nested data from the client to the controller - javascript

I have a form that has two sections. 3 input fields and another section with 10 checkboxes.
public class Customerproductdto
{
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
public string CustomerPhone { get; set; }
List<ProductDetails> GetAllChecked {get;set;}
}
public class ProductDetails
{
public string ProductName{ get; set; }
}
Here is jquery code I am using to get all the values of the checkboxes that were
checked on my form. They are about 10 and users could check everything.
var yourArray[]
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
Here is javascript that I use to collect the data and pass to my controller.
How can I pass in my array here all in one shot?
var objdata =
({
CustomerNumber: txtcustnumber,
CustomerName: txtcustname,
CustomerPhone: txtphone
//How do I pass the yourArray here?
});
var url = "#Url.Action("WriteToDb", "Home")";
var completeData = JSON.stringify({ 'Information': objdata });
$.get(url, { 'objdata': completeData }, function (data) {
$('#mainListContent').html(data);
});
Please note that I will like to deserialize this once I get to the controller.
Here is the method.
public ActionResult WriteToDb(string objdata)
{
Customerproductdto getAllTaskSaved = null;
try
{
var stripOffObjectName = JObject.Parse(objdata)["Information"];
var cleanedData = JsonConvert.DeserializeObject<Customerproductdto>(stripOffObjectName.ToString());
getAllTaskSaved = _dtcDataService.WriteTaskToDb(cleanedData, "Add");
}
catch (Exception ex)
{
logger.Error(ex);
}
return PartialView("_Taskdisplay", getAllTaskSaved);
}

Related

Build a view model for c# using jQuery

I have one view model and i'm pass that view model into controller, but one of the model property is a list of other class. so i'm not able to bind it via jQuery.
I have the following view model.
public class ToolsAddViewModel
{
public string Tools_Name { get; set; }
public string Tools_Desc { get; set; }
public int Category_ID { get; set; }
public List<ToolsParamsBlockViewModel> Params_List { get; set; }
}
ToolsParamsBlockViewModel class that is used as list type
public class ToolsParamsBlockViewModel
{
public int Params_ID { get; set; }
public string Params_CSS_Attribute { get; set; }
public int Params_Priority { get; set; }
}
here is my controller method that handle viewmodel data
[HttpPost]
public ActionResult Manage(ToolsAddViewModel toolsAddViewModel)
{
//insert viewmodel data into database
return RedirectToAction("Index", "Tools");
}
and finally im trying to add data into viewmodel using jQuery, here it is. im use table for add list into Params_List property.
$("#btnSave").on("click", function () {
var ParamsList = [];
$('#paramsBlockTable tbody > tr').each(function () {
var SingleParams = [];
$(this).find("input,select").each(function () {
SingleParams.push($(this).val());
console.log(values);
});
ParamsList.push(values);
});
var ToolsModel = {
"ID": $("#ID").val(),
"Tools_Name": $("#Tools_Name").val(),
"Category_ID": $("#Category_ID").val(),
"Params_List": ParamsList,
"ScriptFiles_IDs": $("#ScriptFiles_IDs").val(),
"Tools_SEO_Keyword": $("#Tools_SEO_Keyword").val(),
"Tools_Desc": $("#Tools_Desc").val(),
}
console.log(ToolsModel);
});
here in ParamsList have array of table row elements but i need it into view model format.
thanks in advance
thanks phuzi its work for me :)
here I have changed some code block.
$("#btnSave").on("click", function () {
var ParamsList = [];
$('#paramsBlockTable tbody > tr').each(function () {
let SingleParams = {
Params_ID: $(this).find(".params-id").val(),
Params_CSS_Attribute: $(this).find(".params-attribute").val(),
Params_Priority: $(this).find(".params-priority").val()
}
ParamsList.push(SingleParams);
});
var ToolsModel = {
"ID": $("#ID").val(),
"Tools_Name": $("#Tools_Name").val(),
"Category_ID": $("#Category_ID").val(),
"Params_List": ParamsList,
"ScriptFiles_IDs": $("#ScriptFiles_IDs").val(),
"Tools_SEO_Keyword": $("#Tools_SEO_Keyword").val(),
"Tools_Desc": $("#Tools_Desc").val(),
}
console.log(ToolsModel);
});

Posting Data in Asp.NET MVC 5 app with JavaScript & ViewModel

The basic problem is this. I'm using CKEditor for an interface for a blog post of sorts. CKEditor gets the wordcount, but I have to use some client-side JavaScript to clean it up. I want to pass the wordcount into the database so I know how many words each post has.
I have a viewmodel for the post:
public class NewStoryViewModel
{
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[Required]
public int Genre { get; set; }
public IEnumerable<Genre> Genres { get; set; }
[Required]
public int StoryType { get; set; }
public IEnumerable<StoryType> StoryTypes { get; set; }
public int WordCount { get; set; }
[Required]
public int StoryAgeRange { get; set; }
public IEnumerable<StoryAgeRange> StoryAgeRanges { get; set; }
[Required]
public int Visibility { get; set; }
public IEnumerable<Visibility> Visibilities { get; set; }
}
And the controller for the post:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult New (NewStoryViewModel viewModel)
{
//confirm form data is valid
if (ModelState.IsValid)
{
//create new story object
var newStory = new Story
{
AuthorId = User.Identity.GetUserId(),
Title = viewModel.Title,
Content = viewModel.Content,
GenreId = viewModel.Genre,
StoryTypeId = viewModel.StoryType,
StoryAgeRangeId = viewModel.StoryAgeRange,
VisibilityId = viewModel.Visibility,
CreatedAt = DateTime.Now,
WordCount = viewModel.WordCount
};
//add new story to db
dbContext.Stories.Add(newStory);
//save db
dbContext.SaveChanges();
return RedirectToAction("Index", "Story");
}
else
{
return View(viewModel);
}
}
On the client-side in the razor view, I have this:
$(document).ready(function () {
$('#addStoryBtn').on('click', function () {
//get the content of the div
var wordcount = $('#cke_wordcount_Content').html();
//chop off the words before the number in the string
var slicedWordCount = wordcount.slice(6);
//remove any excess white space
var trimmedWordCount = slicedWordCount.trim();
//capture the index of the slash
var indexOfSlash = trimmedWordCount.indexOf("/");
//split the string at the slash to get the words used out of the total allotted
var finalWordCount = trimmedWordCount.slice(0, indexOfSlash);
//$.ajax({
// url: "/story/new",
// type: 'POST',
// data: {
// WordCount = finalWordCount
// },
// success: function (data) {
// console.log("Success")
// },
// error: function (error) {
// console.log("error is " + error);
// }
//})
});
});
I do this because CKEditor prints the word count out of the maximum like this:
Words: 4/5000
so I use a bit of JS to remove everything I don't need and keep the number before the slash.
But the ajax post didn't work (stepping through the controller, it returns 0).
I thought about using a hiddenfield in the view. Something like:
#Html.Hidden(new { WordCount = finalWordCount })
But the razor view gives me an error that finalWordCount doesn't mean anything in the current context. I surmise it's because finalWordCount is subject to the button click and since the addPost button hasn't been clicked, finalWordCount is undefined.
Any suggestions on how to pass the wordcount to the viewmodel?
You've mentioned in the comments that you're experiencing a 500 internal server error, which I'm guessing is after you've tried Shyju's suggestion to fix the invalid JSON. My guess is you're unable to even debug the controller action right now because it's expecting an anti-forgery token to be passed to it, but you're not sending that in the body of the POST request.
To fix that, try this:
var form = // selector for your form
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: "/story/new",
type: 'POST',
data: {
__RequestVerificationToken: token,
WordCount: finalWordCount
},
success: function (data) {
console.log("Success")
},
error: function (error) {
console.log("error is " + error);
}
});
That should hopefully fix the validation error, allowing you to at least reach the action.
The MVC application is probably expecting a json format request body, as
that is the default configuration of asp.net MVC.
So before posting the data to the server you need to stringify the model to a proper json.
Try it like this
var data = JSON.stringify({WordCount: finalWordCount});
$.ajax({
url: "/story/new",
type: 'POST',
data: data,
success: function (data) {
console.log("Success")
},
error: function (error) {
console.log("error is " + error);
}
})

Pass an Object from Angularjs to MVC controller and map to Class Object

I have an object in angularjs which I want to pass and map it to custom c# class in mvc controller. but whenever I am doing this class object is null completely.
$scope.Get = function () {
var EService = [{
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
}];
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
})
MVC Controller and Class:
[HttpPost]
public string Insert(ServicesMaster Service)
{
GIBCADBEntities gfientity = new GIBCADBEntities();
var record = "Sent"
return Json(record, JsonRequestBehavior.AllowGet);
} public class ServicesMaster
{
public string id { set; get; }
public string servicename { set; get; }
public string servicetype { set; get; }
public int? monthlyrental { set; get; }
public string serviceremarks { set; get; }
public byte servicestatus { set; get; }
public DateTime? activationdate { set; get; }
public DateTime? deactivationdate { set; get; }
}
The javascript variable/object "EService" is ok here, and when passing only the ServicesMaster object is created with null values and no data is mapped to it. I can send single string or any value from here but when sending a complete object its behaving like this.
You are passing an array from front end and fetching object from server end. just remove the "[" and "]" brace while set value to EService . Like :
$scope.Get = function () {
var Service = {};
Service = {
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
};
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
});
};
It should work now. :)

pass JsonResult object from javascript function in View to Controller

How can I pass JsonResult object from javascript function in View to Controller Action without Ajax call - just javascript - window.location.href = url?
I get JsonResult object from Controller Action to javascript function via Ajax call. Then I want to pass this object back to other Controller Action but I get object with null reference properties.
My javascript function in View:
function order(model) {
$('#details-container').html("<h2>Loading Complete Frame Module. Please wait...</h2>");
$.p({
url: '#Url.Action("CompleteFrameBrandDetails", "PacCompleteFrame")',
data: { item: model },
success: function (xml) {
if (xml.Success) {
$.p({
url: '#Url.Action("GlassCompleteFrame", "PacModule")',
data: JSON.stringify({ b2bXml: xml.Data }),
success: function (model) {
var pacModuleModel = {
Mode: model.Data.Mode,
IframeUrl: model.Data.IframeUrl.toString(),
CustomerNumber: model.Data.CustomerNumber.toString(),
ReadOnly: model.Data.ReadOnly,
GlassXml: model.Data.GlassXml.toString(),
Price: parseFloat(model.Data.Price),
Comission: model.Data.Comission.toString(),
Permissions: null,
Language: model.Data.Language.toString()
};
// here are all values in model.Data correct
// but then I can't figure out how to pass it to Controller Action without Ajax call - just with javascript command
var url = '#Url.Action("GlassCompleteFrameView", "PacModule", "__view__")';
window.location.href = url.replace("__view__", model.Data); //pacModuleModel
}
});
} else {
$.alert({
message: 'error while trying to load xml details'
});
}
}
});
}
My Controller Action:
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return View("Glass", model);
}
I have also Model like this for automatic Json binding but dont work:
public enum ModuleMode
{
ByProduct,
ByRecipe
}
public partial class PacModuleModel
{
private PacPermissionModel permissionModel;
public ModuleMode Mode { get; set; }
public string IframeUrl { get; set; }
public string CustomerNumber { get; set; }
public bool ReadOnly { get; set; }
public string GlassXml { get; set; }
public double? Price { get; set; }
public string Comission { get; set; }
public PacPermissionModel Permissions
{
get
{
if (permissionModel == null)
{
permissionModel = new PacPermissionModel();
}
return permissionModel;
}
}
public string Language { get; set; }
}
Try this in controller
public JsonResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return Json(model, JsonRequestBehavior.AllowGet);
}
The problem was in model. It was more than 45000 char long. Now I use Session variable to get model in GlassCompleteFrameView(PacModuleModel model) and works perfect.
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
model = Session["xml"] as PacModuleModel;
return View("Glass", model);
}

Translate boolean to bool after Ajax call

Hi,
I have a .net class that contains a Boolean, this class is sent to client with AJAX. The problem is that if I just use :
if(MyClass.CheckedValue)
It will always be true even if the CheckedValue is false. I supose that it is instead checking if the object is set and if so it is true? Im note sure what type this Boolean propertie gets when returning to the javascript after AJAX?
I have also tried this :
var checked;
checked = Boolean(this.CheckedValue === 'true');
if (checked)
But this will also laways be true?
How do I handle this?
Edit1 :
The classes that is sent to client :
/// <summary>
/// Are set to client with Ajax to render a correct view of the
/// current category and filter settings
/// </summary>
public class GetCategoriesAndFiltersAjax
{
public GetCategoriesAndFiltersAjax()
{
Filters = new Filter();
}
public SelectList categoryList { get; set; }
public Filter Filters { get; set; }
public class Filter
{
public Filter()
{
DefaultFilters = new List<CategoryItemFilter>();
FilterList = new List<CategoryItemFilter>();
}
/// <summary>
/// Filters like buy, sell, let and so on
/// </summary>
public List<CategoryItemFilter> DefaultFilters { get; set; }
/// <summary>
/// All other filters that a category might be bound to
/// </summary>
public List<CategoryItemFilter> FilterList { get; set; }
}
}
public class CategoryItemFilter
{
private int _filterId = -1;
private string _clientElementId1;
private string _clientElementId2;
public FilterControlType FilterControlType { get; set; }
public string Title1 { get; set; }
public string Title2 { get; set; }
public string ClientElementId1
{
get { return _clientElementId1; }
set
{
_clientElementId1 = value;
}
}
public string ClientElementId2
{
get { return _clientElementId2; }
set
{
_clientElementId2 = value;
}
}
/// <summary>
/// Keep track of whitch filter it is
/// </summary>
public int FilterId
{
get { return _filterId; }
set { _filterId = value; }
}
#region Values
public Boolean CheckedValue { get; set; }
public string TextValue { get; set; }
public SelectList DropDownList1 { get; set; }
public SelectList DropDownList2 { get; set; }
#endregion
public PublicAdFilterKey PublicAdFilterKey { get; set; }
}
And this is how the AJAX method looks like on server :
public JsonResult GetCategoriesByParent(int id, Boolean editMode)
{
FilterModel filterModel = new FilterModel();
CategoryModel categoryModel = new CategoryModel();
List<ModelViewCategory> mvCategoryList = new List<ModelViewCategory>();
//List<AdCategory> categoryList;
FilterHandler filterHandler = new FilterHandler();
GetCategoriesAndFiltersAjax value = new GetCategoriesAndFiltersAjax();
try
{
value.categoryList = new SelectList(categoryModel.GetCategoriesByParent(id).ToArray(), "Id", "Name");
if (editMode)
value.Filters = filterHandler.ConvertFilterModelToAjaxCategoryFilter(filterModel.GetCategoryFilterByCategory(id), Biss.Views.ViewClasses.Filter.FilterType.Edit);
else
value.Filters = filterHandler.ConvertFilterModelToAjaxCategoryFilter(filterModel.GetCategoryFilterByCategory(id), Biss.Views.ViewClasses.Filter.FilterType.Display);
return this.Json(value, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw;
}
}
Edit 2 :
This is how the client looks like(not exacly but close, its alot more complicated)
$.ajax({
url: actionPath,
type: 'POST',
dataType: 'json',
data: ((typeof config.postData == "function") ? config.postData() : config.postData) || { id: $(source).val(), editMode: _filterInEditMode },
success: function (data) {
methods.reset();
$.each(data.categoryList, function () {
SetFilterSubEdit(data.DefaultFilters);
},
error: function () {
methods.showError();
}
});
function SetFilterSubEdit(data) {
$.each(data, function () {
if (data.CheckedValue)
$("#" + visibleElements[0]).attr('checked', checked);
}
}
Sorry, the problem was that the brackets was missing on client side.
if (data.CheckedValue){
}

Categories

Resources