View not update after POST although View Model updated - asp.net

I am writing ASP.NET Custom Component, I want to update my view with following code below:
#if (Model.TableDatasource != null){
//Write some thing to html page example: tables or span
}
At the first, Model.TableDatasource is null, user choose information and Controller Review View(Model) like this:
var model = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
};
if (request == null)
{
return View(model);
}
else
{
var currentPlant = JsonConvert.DeserializeObject<PlantList>(request);
var FullModel = new PrintDeliveryTicketModel()
{
PlantList = CommonHelper.GetPlantList(),
CurrentPlant = JsonConvert.DeserializeObject<PlantList>(request),
DriverList = JsonConvert.DeserializeObject<List<Drivers>>(CommonHelper.GetDriver(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
CustomerList = JsonConvert.DeserializeObject<List<Customer>>(CommonHelper.GetCustomer().Content.ReadAsStringAsync().Result),
RecipeList = JsonConvert.DeserializeObject<List<Recipe>>(CommonHelper.GetRecipe(currentPlant.CodePlant, currentPlant.PlantNo.Value).Content.ReadAsStringAsync().Result),
SitesList = JsonConvert.DeserializeObject<List<Site>>(CommonHelper.GetSite().Content.ReadAsStringAsync().Result),
// TruckList = JsonConvert.DeserializeObject<List<Truck>>(CommonHelper.GetTruck().Content.ReadAsStringAsync().Result)
};
return View(FullModel);
}
At the Debug time, I notice that break-point stop at return View(FullMode) and Break-point at ViewFile(cshtml) has value. but nothing printed at view.
Hope some help.

Related

Loading a menu structure on every razor page in asp .NET Core

After user authentication I'm supposed to change the user menu based on the roles of the user.
To do this, I created a service which fetched the menu the user is expected to see:
public List<MenuStructure> LoadCompleteMenuRole(string role)
{
List<MenuStructure> resultList = null;
var menuHeaders = LoadMenuHeadersForTheGivenRole(role);
if (menuHeaders != null && menuHeaders.Count > 0)
{
resultList = new List<MenuStructure>();
foreach (var menuHeader in menuHeaders)
{
var menuStructure = new MenuStructure
{
MenuName = menuHeader.HeaderName,
Caption = menuHeader.Caption
};
var menuDetails = LoadMenuDetailsForTheGivenHeader(menuHeader.Id);
if (menuDetails != null && menuDetails.Count > 0)
{
menuStructure.MenuElements = new List<MenuElement>();
foreach (var menuDetail in menuDetails)
{
var menuElement = new MenuElement
{
ElementName = menuDetail.DetailName,
ElementCaption = menuDetail.Caption,
Destination = menuDetail.Destination
};
menuStructure.MenuElements.Add(menuElement);
}
}
resultList.Add(menuStructure);
}
}
return resultList;
}
My problem? Where do I implement the service so the menus get loaded in every razor page I create?

Post data with free-jqgrid, what are the code in client and Web API side?

I am using ASP.NET MVC 6 Web API. In the View I use free-jqgrid.
Let's borrow Oleg's free jqgrid data to demonstrate my purpose. We already have the table shown.
Next I am going to add new Vendor. Please notify that there is primary key id(identity column) in the database. We don't want it displaying in the screen.
In VendorRespository.cs, I add the new Vendor as
public void AddVendor(Vendor item)
{
using (VendorDataContext dataContext = new VendorDataContext())
{
dataContext.Database.Connection.ConnectionString = DBUtility.GetSharedConnectionString(
"http://centralized.admin.test.com");
var newVendor = dataContext.Vendors.Create();
newVendor.Company = item.Company;
newVendor.ContactName = item.ContactName;
newVendor.ContactPhone = item.ContactName;
newVendor.UserName = item.UserName;
newVendor.UserKey = item.UserKey;
newVendor.Active = item.Active;
newVendor.FacilityId =item.FacilityId;
newVendor.ClientID = item.ClientID;
dataContext.SaveChanges();
}
}
My questions:
Not sure the script like?
<script>
API_URL = "/VendorManagement/";
function updateDialog(action) {
return {
url: API_URL
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) { }
, modal: true
, onclickSubmit: function (params) {
var list = $("#jqgrid");
var selectedRow = list.getGridParam("selrow");
rowData = list.getRowData(selectedRow);
params.url += rowData.Id;
params.mtype = action;
}
, width: "300"
};
}
jQuery("#jqgrid").jqGrid('navGrid',
{ add: true, edit: true, del: true },
updateDialog('PUT'),
updateDialog('POST'),
updateDialog('DELETE')
);
In the controller, not sure what is the code?
// POST
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
My code has many compiling errors such as
'HttpRequest' does not contain a definition for 'CreateResponse' and the best extension method overload 'HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage, HttpStatusCode, Vendor)' requires a receiver of type 'HttpRequestMessage'
Please help me to get rid of the error and inappropriate code.
EDIT:
I borrowed the code snippet from here.
I need add the code such as
[Microsoft.AspNet.Mvc.HttpGet]
public dynamic GetVendorById(int pkey)
{
return null;
}
And
// POST
[System.Web.Http.HttpPost]
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("/VendorManagement/GetVendorById", new { id = item.pkey });
response.Headers.Location = new Uri(uri);
return response;
}

If statement in Controller not saving changes

I have an if statement in my Controller which decides whether a checkbox is checked or not.
It works fine in the if statement and changes the properties, but when i go to send it back to the view these changes aren't saved.
Controller
public ActionResult GetUserRights(string userLogin)
{
if (userLogin != null)
{
Manager manager = new Manager();
var userlogin = manager.GetUserData(userLogin);
var userrights = userlogin.RightsId.Select(s => new { id = s, text = s });
var rightdetails = manager.GetAllRightsRows();
var rightsDetails = from r in rightdetails
orderby r.Id
select new RightDetail
{
RightID = r.Id,
RightDescription = r.Description,
RightName = r.Name,
ParentID = r.ParentId,
TypeColor = r.TypeColor,
Value = r.Value,
Checked = false
};
foreach (var userright in userrights)
{
foreach (var rightdets in rightsDetails)
{
if(rightdets.RightID == userright.id)
{
rightdets.Checked = true;
break;
}
}
}
return View("_RightsTreeListPartial", rightsDetails); <==== ALL CHECKED
PROPERTIES ARE false EVEN THOUGH SOME ARE BEING CHANGED IN THE IF STATEMENT.
}
return View("Index");
}
Let me know if you need any more info.
Thanks
With an IEnumerable, I am not sure of the reason why, but you cannot edit an item using an if statement so the code below is correct and does what it is supposed to, however as it is IEnumerable non of the changes are saved, also the process below is very heavy and long winded for what we need to do.
Original Code
foreach (var userright in userrights)
{
foreach (var rightdets in rightsDetails)
{
if(rightdets.RightID == userright.id)
{
rightdets.Checked = true;
break;
}
}
}
The new code takes a lot less time and will therefore improve the wait time. Firstly the IEnumerable is converted to a List, then, using a for-loop, the data is iterated through until a match is found, then within an if statement the item is changed (using original code and just converting from IEnumerable to List should work but I wouldn't recommend using it).
New Code
var rightdetail = rightsDetails.ToList();
foreach (var userright in userrights)
{
for (var i = 0; i < rightdetail.Count(); i++)
{
if (rightdetail[i].RightID == userright.id)
{
rightdetail[i].Checked = true;
break;
}
}
}

Retrieving CRM 4 entities with custom fields in custom workflow activity C#

I'm trying to retrieve all phone calls related to opportunity, which statecode isn't equal 1. Tried QueryByAttribute, QueryExpression and RetrieveMultipleRequest, but still has no solution.
Here some code i wrote.
IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
IWorkflowContext context = contextService.Context;
ICrmService crmService = context.CreateCrmService(true);
if (crmService != null)
{
QueryByAttribute query = new Microsoft.Crm.Sdk.Query.QueryByAttribute();
query.ColumnSet = new Microsoft.Crm.Sdk.Query.AllColumns();
query.EntityName = EntityName.phonecall.ToString();
query.Attributes = new string[] { "regardingobjectid" };
query.Values = new string[] { context.PrimaryEntityId.ToString() };
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
return ActivityExecutionStatus.Closed;
}
And almost same for QueryExpression
QueryExpression phCallsQuery = new QueryExpression();
ColumnSet cols = new ColumnSet(new string[] { "activityid", "regardingobjectid" });
phCallsQuery.EntityName = EntityName.phonecall.ToString();
phCallsQuery.ColumnSet = cols;
phCallsQuery.Criteria = new FilterExpression();
phCallsQuery.Criteria.FilterOperator = LogicalOperator.And;
phCallsQuery.Criteria.AddCondition("statuscode", ConditionOperator.NotEqual, "1");
phCallsQuery.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId.ToString();
I always get something like Soap exception or "Server was unable to proceed the request" when debugging.
To get exception details try to use following code:
RetrieveMultipleResponse retrieved = null;
try
{
retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
catch(SoapException se)
{
throw new Exception(se.Detail.InnerXml);
}

how to pass value of viewmodel from controller to another controller

i try to create some application using MVC 4. in my application, i can create new promo. how can i pass value from Create to Index when i using ViewModel for parameter in Index.
this my Index
public ActionResult Index(ViewModel.Rate.RateViewModel search)
{
var RoomType = _RoomTypeService.GetRoomTypeName(_HotelID);
var currency = _CurrencyService.GetAllCurrency();
XNet.WebUI.Hotel.ViewModel.Rate.RateViewModel vm = new ViewModel.Rate.RateViewModel();
if (search.Request == null)
{
vm.RoomTypeList = ViewModel.DropDown.Builder.RoomTypeBuilder.Build(RoomType, null);
vm.CurrencyList = ViewModel.DropDown.Builder.CurrencyBuilder.Build(currency, null);
}
else
{
vm.RoomTypeList = ViewModel.DropDown.Builder.RoomTypeBuilder.Build(RoomType, search.Request.RoomTypeID);
vm.CurrencyList = ViewModel.DropDown.Builder.CurrencyBuilder.Build(currency, search.Request.Currency);
}
vm.Request = search.Request;
if (search.Request == null)
{
vm.Request = new RateRequest();
vm.Request.CheckInFrom = null;
vm.Request.CheckInTo = null;
vm.Request.RoomTypeID = null;
}
if (search.Request != null)
{
Session["RoomTypeID"] = search.Request.RoomTypeID;
Session["Breakfast"] = search.Request.Breakfast;
Session["Currency"] = search.Request.Currency;
}
vm.listRoomRate = GetDataIndex(vm.Request);
_UserSession.SearchRoomRate = vm;
return RedirectToAction("SearchResult");
}
my New
[HttpPost]
public ActionResult New(ViewModel.Rate.RateViewModel vm)
{
if (vm.NewRoomRate.Currency == null)
vm.NewRoomRate.Currency = "IDR";
var NewData = _RoomRateService.NewRoomRate(vm.NewRoomRate.RoomTypeName, vm.NewRoomRate.Breakfast,
Convert.ToDateTime(vm.NewRoomRate.CheckInFrom), Convert.ToDateTime(vm.NewRoomRate.CheckInTo), vm.NewRoomRate.sun, vm.NewRoomRate.mon, vm.NewRoomRate.tue,
vm.NewRoomRate.wed, vm.NewRoomRate.thu, vm.NewRoomRate.fri, vm.NewRoomRate.sat, vm.NewRoomRate.Currency, vm.NewRoomRate.SingleRate,
vm.NewRoomRate.DoubleRate, vm.NewRoomRate.TripleRate, Convert.ToDecimal(vm.NewRoomRate.Commision), Convert.ToInt32(vm.NewRoomRate.Allotment), vm.NewRoomRate.CloseSelling,
vm.NewRoomRate.FreeSell);
if (NewData == null)
{
ModelState.AddModelError("failed", "RoomRate is already created, please use edit instead");
return New();
}
ViewModel.Rate.RateViewModel test = new ViewModel.Rate.RateViewModel();
test.Request = new RateRequest();
test.Request.RoomTypeID = Convert.ToInt32(vm.NewRoomRate.RoomTypeName);
return RedirectToAction("Index", new {search = test.Request });
}
i try like this, but i get error like this
Server Error in '/' Application.
The model item passed into the dictionary is of type '<>f__AnonymousType0`1[XNet.WebUI.Hotel.ViewModel.RateRequest]', but this dictionary requires a model item of type 'XNet.WebUI.Hotel.ViewModel.Rate.RateViewModel'.
can some one tell me, how i can do this?
thanks
according to the error you are getting:
Server Error in '/' Application.
The model item passed into the dictionary is of type '<>f__AnonymousType0`1[XNet.WebUI.Hotel.ViewModel.RateRequest]', but this dictionary requires a model item of type 'XNet.WebUI.Hotel.ViewModel.Rate.RateViewModel'.
you are specifying that Index will recieve a parameter of type: ViewModel.Rate.RateViewModel named search.
public ActionResult Index(ViewModel.Rate.RateViewModel search)
but you are passing an object of type ViewModel.Rate.RateViewMode in your "NEW" action result.
ViewModel.Rate.RateViewModel test = new ViewModel.Rate.RateViewModel();
test.Request = new RateRequest();
test.Request.RoomTypeID = Convert.ToInt32(vm.NewRoomRate.RoomTypeName);
return RedirectToAction("Index", new {search = test.Request });
to resolve the error you can edit your controller like this:
[HttpPost]
public ActionResult New(ViewModel.Rate.RateViewModel vm)
{
if (vm.NewRoomRate.Currency == null)
vm.NewRoomRate.Currency = "IDR";
var NewData = _RoomRateService.NewRoomRate(vm.NewRoomRate.RoomTypeName, vm.NewRoomRate.Breakfast,
Convert.ToDateTime(vm.NewRoomRate.CheckInFrom), Convert.ToDateTime(vm.NewRoomRate.CheckInTo), vm.NewRoomRate.sun, vm.NewRoomRate.mon, vm.NewRoomRate.tue,
vm.NewRoomRate.wed, vm.NewRoomRate.thu, vm.NewRoomRate.fri, vm.NewRoomRate.sat, vm.NewRoomRate.Currency, vm.NewRoomRate.SingleRate,
vm.NewRoomRate.DoubleRate, vm.NewRoomRate.TripleRate, Convert.ToDecimal(vm.NewRoomRate.Commision), Convert.ToInt32(vm.NewRoomRate.Allotment), vm.NewRoomRate.CloseSelling,
vm.NewRoomRate.FreeSell);
if (NewData == null)
{
ModelState.AddModelError("failed", "RoomRate is already created, please use edit instead");
return New();
}
ViewModel.Rate.RateViewModel test = new ViewModel.Rate.RateViewModel();
return RedirectToAction("Index", new {search = test });
}
hope that helps.

Resources