Build a view model for c# using jQuery - javascript

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

Related

MVC core 5.0 update js via Viewmodel

im trying to update data in javascript via viewmodel.
When the side loads it works.
window.addEventListener('load', function () {
let listModel = #Html.Raw(Json.Serialize(Model));
LoadAllInfoSpots(listModel);
});
But when i call my js function
function afterClickOnFlorplan() {
setTimeout(function () {
let listModel =#Html.Raw(Json.Serialize(Model));
LoadAllInfoSpots(listModel);
}, 1500);
}
the let listmodel is the same as when i loaded the side. with a count of 4.
i know the viewmodel is updating.
but as you can see let listmodel is not updated in my js code.
So why is the let listmodel the same all the time?
hope you can help me.
Model:
public class SelectorModel
{
public int? ID { get; set; }
public string ImageName { get; set; }
public string Cords { get; set; }
public string Name { get; set; }
}
ViewModel:
public class SelectorViewModel
{
public List<SelectorModel> SelectorModels { get; set; }
}
the first IActionResult:
public IActionResult Index()
{
LoadInfoSpotsFromDB load = new LoadInfoSpotsFromDB();
string first = load.LoadFirstImage();
SetFirstIMageCookie(first);
List<SelectorModel> loaede = load.Load(first);
selectorViewModel = new SelectorViewModel
{
SelectorModels = loaede
};
return View(selectorViewModel);
}
the IActionResult that update the ViewModel
[HttpPost]
public IActionResult Index([FromBody] string dontremove)
{
selectorViewModel = null;
LoadInfoSpotsFromDB load = new LoadInfoSpotsFromDB();
List<SelectorModel> loaede = load.Load(HttpContext.Request.Cookies["ImageName"]);
selectorViewModel = new SelectorViewModel
{
SelectorModels = loaede
};
return View(selectorViewModel);
}

When creating double dropdown SelectList with JQuery on POST returns 0. ASP.Net CORE 2.1

I have created two dropdownlists, of which one acts as a filter for the other. So, with dropdown Customer a customer is selected and only a limited set of ClientUsers is presented in in the dropdown ClientUser. I use a Jquery function to make this happen.
The selection works excellent, but when I POST the form the ClientUser is set to 0, instead of the choice.
The View is as follows (simplified for readability purposes):
#model DropDownTester2.Models.CaseViewModel
<form asp-action="Maak">
<label asp-for="CaseTitle" class="control-label"></label>
<input asp-for="CaseTitle" class="form-control" />
<select id="customerId" asp-for="CustomerId" asp-items='#(new SelectList(ViewBag.customers, "CustomerId", "CompanyName"))'>
<option>Select Customer Name</option>
</select>
<select id="clientUserId" asp-for="ClientUserId" asp-items='#(new SelectList(string.Empty, "ClientUserId", "LastName"))'>
</select>
<input type="submit" value="Maak" class="btn btn-default" />
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#customerId").change(function () {
var url = '#Url.Content("~/")' + "Case/getClientUserById";
var ddlsource = "#customerId";
$.getJSON(url, { id: $(ddlsource).val() }, function (data) {
//$.getJSON("#Url.Action("getClientUserById","Case")", { id: $(ddlsource).val() }, function (data) {
var items = '';
$("#clientUserId").empty();
$.each(data, function (i, row) {
items += "<option value='" + row.value + "'>" + row.text + "</option>";
});
$("#clientUserId").html(items);
})
});
});
</script>
}
The CaseViewModel is:
public class CaseViewModel
{
public int CaseId { get; set; }
public string CaseTitle { get; set; }
public int CustomerId { get; set; }
public int ClientUserId { get; set; }
public IEnumerable<Customer> CustomerList { get; set; }
public IEnumerable<ClientUser> ClientUserList {get; set;}
My Model for Case is:
public class Case
{
public int CaseId { get; set; }
public string CaseTitle { get; set; }
public string CaseRoleDescription { get; set; }
public int CustomerId { get; set; }
public int ClientUserId { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<ClientUser> ClientUsers { get; set; }
}
Finally my controllers are :
// GET: Case/Maak
public IActionResult Maak()
{
ViewBag.customers = _context.Customer.ToList();
return View();
}
public JsonResult getClientUserById(int id)
{
List<ClientUser> list = new List<ClientUser>();
list = _context.ClientUser.Where(c => c.Customer.CustomerId == id).ToList();
list.Insert(0, new ClientUser { ClientUserId = 0, LastName = "Please select a clientuser" });
return Json(new SelectList(list, "ClientUserId", "LastName"));
}
// POST: Case/Maak
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Maak(CaseViewModel model)
{
if (ModelState.IsValid)
{
var newCase = new Case
{
CaseId = model.CaseId,
CaseTitle = model.CaseTitle,
CustomerId = model.CustomerId,
ClientUserId = model.ClientUserId
};
_context.Add(newCase);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["CustomerId"] = new SelectList(_context.Set<Customer>(), "CustomerId", "CustomerId", model.CustomerId);
return View(model);
}
I can't reproduce your issue :
The difference part of codes is that i create the Customer/ClientUser manually but that shouldn't be the issue cause :
public class Customer {
public int CustomerId { get; set; }
public string CompanyName { get; set; }
}
public class ClientUser
{
public int ClientUserId { get; set; }
public string LastName { get; set; }
}
You may search the "ClientUserId " in your pages to confirm whether other function reset the value .
As a workaround, you can also :
Create a hidden filed in your page and bind to your model property , create the select change event javascript function to set the value based on the selection .
Use Jquery to get the selected opinion , use Ajax to call action function and pass the value as parameter .

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. :)

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

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

KendoUI treeview children are displayed as undefined

I have a treeview in kendoUI in which main nodes are calling into an mvc controller and that controller looks to whether there is an nullable id passed in and then uses a different model.
What I hit the url : http://localhost:2949/Report/GetReportGroupAssignments
I see this JSON
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4}
]
Now my mvc controller looks like this
public JsonResult GetReportGroupAssignments(int? id)
{
var model = new List<ReportGroup>();
var defModel = new List<ReportDefinition>();
try
{
if (id == null)
{
model = _reportService.GetReportGroups("en-us").ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
else
{
defModel = _reportService.GetReportDefinitions().Where(e=>e.ReportGroupID ==Convert.ToInt32(id)).ToList();
return Json(defModel, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Logger.Error(ex, "Error loading LoadReportList.");
return null;
}
}
My Kendo javascript looks like the following:
var serviceRoot = "/Report"; // "//demos.telerik.com/kendo-ui/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments", //"/LoadReportTree", // "/Employees",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,hasChildren: "Id"
}
}
});
var treeview = $("#treeview").kendoTreeView({
expanded: true,
dragAndDrop: true,
dataSource: homogeneous,
dataTextField: "ReportGroupName"
}).data("kendoTreeView");
Seems that the calls (which I discovered that children records have a "load" method that it called behind the seens, so basically I pass in the ID in order to get the data from the other model ( table in db)
(Id is mapped with automapper to ReportGroupID )
So when i click to the left of "Standard Rports" I am getting all of these children as undefined, How do I get these to show up properly?
Update: My ReportDefinition class:
public class ReportDefinition {
public override int Id { get; set; }
public string ReportKey { get; set; }
public string ReportName { get; set; }
public int? ReportNameResID { get; set; }
public string ReportDef { get; set; }
public int? ReportDefinitionResID { get; set; }
public string ReportAssembly { get; set; }
public string ReportClass { get; set; }
public int ReportGroupID { get; set; }
public int AppID { get; set; }
public int SortOrder { get; set; }
public bool IsSubReport { get; set; }
}
I think your problem is that the class ReportDefinition does not have a property called: ReportGroupName. That is why TreeView displays 'undefined'.
Try adding this Property to your ReportDefinition class like:
public class ReportDefinition {
// Other Properties
// I guess this property is missing
public string ReportGroupName { get; set; }
}

Categories

Resources