|
Hi,
I bind a detailsview/grid, etc. via ODS to an EF-object, maybe a SQL-Query with calculated fields, unions, unpivot, etc. To this source i can't do an update with db.Savechanges(), i have to update the orign table. I tried, but maybe i used different context. I used the same but no success. No error at SaveChanges to the orign table, but the changed data is not in the SQL-DB. Maybe because of the binding?
How can i select from ODS and update to EF-Object?
Thanks for help!
|
|
|
|
|
|
Thanks, but something like this would work, too:
db.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
And work with the same context, or use attach/detach.
|
|
|
|
|
|
C# code
protected void Page_Load(object sender, EventArgs e)
{
string markers = GetMarkers();
string map = @"
<script type='text/javascript' src='http://maps.googleapis.com/maps/api/js?sensor=false&key=keyvalue'></script>
<script type='text/javascript'>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(28.3213, 77.5435),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById('mapArea'),
mapOptions);" + markers + @"}
</script>
";
Page.ClientScript.RegisterStartupScript(this.GetType(), "initialize", map, false);
}
protected string GetMarkers()
{
string markers = "";
SqlConnection conn = new SqlConnection();
conn.ConnectionString =ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
{
SqlCommand cmd = new SqlCommand("SELECT Latitude, Longitude, RegistrationNumber FROM DriverLocation", conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
markers +=
@"var marker" + i.ToString() + @" = new google.maps.Marker({
position: new google.maps.LatLng(" + reader["Latitude"].ToString() + ", " +
reader["Longitude"].ToString() + ")," +
@"map: myMap,
title:'" + reader["RegistrationNumber"].ToString() + "'});";
}
}
return markers;
}
}
html code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="mapArea" style="width: 500px; height: 500px;">
</div>
</form>
</body>
</html>
|
|
|
|
|
You never call your initialize function. You should pass it as the callback parameter to the maps API script:
string map = @"
<script type='text/javascript' src='http://maps.googleapis.com/maps/api/js?key=keyvalue&callback=initialize'></script>
..."
Getting Started | Google Maps JavaScript API | Google Developers[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi,
I would like to have a Base Model and use it in my _Shared view. I followed some examples online and did the following but I was unable to make it work:
_Layout view:
@model Portal.Models.BaseViewModel
Hi, @Model.FirstName
Base Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Portal.Models
{
public class BaseViewModel
{
public String FirstName { get; set; }
}
}
Base Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Portal.Models;
namespace Portal.Controllers
{
public class BaseController : Controller
{
public BaseController()
{
BaseViewModel baseModel = new BaseViewModel()
{
FirstName = "John"
};
}
}
}
Dashboard Controller:
public class DashboardController : BaseController
When I run the application, I get the following error for @Model.FirstName:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Am I missing something?
Thank you for your time and consideration.
|
|
|
|
|
It's probably because -
1. you do not have constructor for BaseViewModel to assign any default value to FirstName(which you can access if no other value assigned to it), you have just declared the property for get and set.
2. In any of BaseController or DashboardController you do not have property which hold data for BaseViewModel. On BaseController you have created it but not assigned to anything.
Try something like below and then access "BaseController.baseModel" to pull value of FirstName
public class BaseController : Controller
{
BaseViewModel baseModel;
public BaseController()
{
baseModel = new BaseViewModel()
{
FirstName = "John"
};
}
}
modified 20-Sep-20 21:01pm.
|
|
|
|
|
Thank you for your help
modified 3-Jun-17 11:56am.
|
|
|
|
|
codeproject registration page show a dropdown which show client timezone and client can change it during registration. so i like to know how codeproject registration page knows what is client timezone at their server end because we know that from server end we can not detect client timezone. only at client side we can detect client's timezone by javascript.
so please any codeproject moderator tell me how they show client timezone selected in their dropdown in registration page. just give me some idea.
|
|
|
|
|
|
thanks great
|
|
|
|
|
Hi,
I have a Web Api Get implemented in the following way
public object Get()
{
dynamic model = null;
using (AppDevSecEntities ctx = new AppDevSecEntities())
{
BSCCrystalReportsViewerEntities ctx2 = new BSCCrystalReportsViewerEntities();
string maxLanId = ctx.UserLists.OrderByDescending(x => x.LastName).First().WindowsUserName;
var tempUserJobs = (from c in ctx.UserJobs orderby c.SupervisorUserName select c).Where(x => x.WindowsUserName == maxLanId);
DataTable UserJobs = Common.ConvertToDataTable<UserJob>(tempUserJobs);
model =
new
{
SingleEmployee = ctx.spGetShortSingleEmployee(maxLanId).FirstOrDefault(),
Departments = (from c in ctx.Departments orderby c.DepartmentName select c).ToList<Department>(),
Locations = (from c in ctx.Locations orderby c.LocationName select c).ToList<Location>(),
Supervisors = (from c in ctx.Supervisors orderby c.LastName, c.FirstName select c).ToList<Supervisor>(),
Managers = (from c in ctx.Managers orderby c.LastName, c.FirstName select c).ToList<Manager>(),
Directors = (from c in ctx.Directors orderby c.LastName, c.FirstName select c).ToList<Director>(),
Applications = (from c in ctx.Applications orderby c.ApplicationName select c).ToList<Application>(),
ApplicationGroups = (from c in ctx.ApplicationGroups orderby c.ApplicationGroupName select c).ToList<ApplicationGroup>(),
ApplicationSecurityRoles = (from c in ctx.ApplicationSecurityRoles orderby c.ApplicationSecurityRoleName select c).ToList<ApplicationSecurityRole>(),<br />
UserJobs
};
}
return model;
}
I have jquery call to get this in the Employee.js file as below
loadEmployee: function (employeeID) {
$.get("/api/EmployeeAPI/Get").then(function (data) {
var list = $("#ddlApplicationGroup");
var selectedValue = list.val();
list.empty();
$.each(data.ApplicationGroups, function (index, applicationgroup) {
$("<option>").attr("value", applicationgroup.ApplicationGroupID).text(applicationgroup.ApplicationGroupName).appendTo(list);
});
if ((selectedValue == null) || (selectedValue == undefined)) {
list.prepend("<option value='-1' selected='selected'>Select value</option>");
list[0].selectedIndex = 0;
}
else {
list.val(selectedValue);
}
});
}
Now I want to bind UserJobs with a table in the cshtml, the table id is: tableDisplay, the condition is I want to loop through the rows and columns with the Column and Row index rather instead of Column Names. Can anybody please help me in this regards?
As I am not supposed to know the Column names or create this table as general table to fit for all the DataTable, I am trying to loop and read through the table and assign the value to cells.
Here I am trying but failing
var a = data.UserJobs;
var columns = a.api.columns();
a.columns().every(function () {
alert(a[0].val();<br />
});
$.each(a, function (bb) {
alert(a[bb][0]);
});
Any help is going to be very very helpful, thanks in advance.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
-- modified 30-May-17 16:38pm.
|
|
|
|
|
Hi all,
I am having trouble sending a success/fail message to a view from my controller. I have a file upload section of my website. User chooses file, presses upload button and file is saved in a folder.
My Controller code:
public ActionResult UploadFiles(int? id)
{
CI cI = db.DataBase.Find(id);
foreach (string upload in Request.Files)
{
if (Request.Files[upload].FileName != "")
{
string path = Server.MapPath(@"/App_Data/uploads/" + id + "/");
string filename = Path.GetFileName(Request.Files[upload].FileName);
Response.Write(path);
bool check = System.IO.File.Exists(Path.Combine(path, filename));
if (check==true)
{
Session["msg"] = "File with the same name already exists - Choose another file or change the file name";
System.Diagnostics.Debug.Write("file exists");
return RedirectToAction("UploadFiles");
}
if (check == false)
{
Session["msg"] = "Successfull Upload";
Request.Files[upload].SaveAs(Path.Combine(path, filename));
System.Diagnostics.Debug.Write("Upload success");
return RedirectToAction("UploadFiles");
}
}
}
return View("Upload");
}
Then I am calling the message in my view using:
@Session["msg"];
The code is working for the most part i.e. it will check if the file exists/doesn't correctly and print the correct message to the output. My problem is getting the message to the view. If I manually refresh the page my message gets to the view. So that tells me I am making a mistake with how I am redirecting.
I am quite new to Mvc so I can't identify the problem. Any help would be greatly appreciated.
|
|
|
|
|
This might be a caching issue, so when the browser requests the UploadFiles page it shows the cached version rather than asking for a new version so your message isn't there. If that's the case you can "fix" this by adding something random to the url
return RedirectToAction("UploadFiles", new { r = DateTime.Now.Ticks.ToString() });
that will add an "r" param with a pseudo-random number forcing the browser to get an updated version of the page.
|
|
|
|
|
Thanks for your answer.
Unfortunately it did not solve my issue.
The code seems to be operating as expected when using breakpoints, it is getting to the RedirectToAction line but no reload. Refresh browser and message is there!
|
|
|
|
|
Use the network tools of the browser to examine the network traffic and look at the statuses etc to see if it really is getting a cached version or not and to see if the redirect is happening etc.
|
|
|
|
|
In MVC , ViewBag , ViewData and TempDate are preferred than Session. In your case , try TempData.
|
|
|
|
|
Thanks for your reply.
I have been using all three ViewBag, TempData & Session while testing but to no avail. I agree Temp data is the best here. From my little knowledge, I have read that it is best practice to use TempData for redirects.
|
|
|
|
|
Can you show us the code for
return RedirectToAction("UploadFiles"); ?
Are you able to see the Session['msg'] in there before View.
|
|
|
|
|
RedirectToAction is a built-in method provided by the MVC framework, it's not something he has written himself.
|
|
|
|
|
I meant the
"UploadFiles" where he is redirecting to.
|
|
|
|
|
Hi everyone,
Firstly, thanks for trying to help me out with this. I have fixed the issue. The problem was not in the controller, it was in fact the view.
My problem is I am completely new to this type of coding, In fact, up to a couple of months ago, the only programming I had dabbled in was matlab for scientific analysis purposes. I probably should spend more time learning the basics, but as I have absolutely no patience, I have decided to build first and analyse later.
I would appreciate it if I could get some help understanding where I went wrong.
The view I was using was utilizing Ajax. Data was added to the form data collection and then passed to the controller via Ajax call.
The View:
@{
ViewBag.Title = "Upload";
}
<h2>Upload</h2>
<script src="~/Scripts/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function () {
$(‘#btnUploadFile’).on(‘click’, function () {
var data = new FormData();
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
data.append("UploadedImage", files[0]);
}
var ajaxRequest = $.ajax({
type: "POST",
url: "",
contentType: false,
processData: false,
data: data
});
ajaxRequest.done(function (xhr, textStatus) {
});
});
});
</script>
<input type="file" name="FileUpload1″ id="fileUpload" /><br />
<input id="btnUploadFile" type="button" value="Upload File" />
@Html.ActionLink("Documents", "Downloads")
<p>
@TempData["msg"]
</p>
I had a feeling (Uneducated guess!)that using the Ajax request was the problem so I changed my approach. I used the Html.BeginForm() extension method
I changed my view to:
@using (Html.BeginForm("UploadFiles", "CIsAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FileUpload1" /><br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
@Html.ActionLink("Documents", "Downloads")
<p>
@TempData["msg"]
</p>
Can someone explain in simple terms, what the issue was?
FYI, this is my controller code:
public ActionResult UploadFiles(int? id,string msg)
{
CI cI = db.LotusCIs.Find(id);
foreach (string upload in Request.Files)
{
if (Request.Files[upload].FileName != "")
{
string path = Server.MapPath(@"/App_Data/uploads/" + id + "/");
string filename = Path.GetFileName(Request.Files[upload].FileName);
Response.Write(path);
bool check = System.IO.File.Exists(Path.Combine(path, filename));
if (check==true)
{
TempData["msg"] = "File with the same name already exists - Choose another file or change the file name";
return RedirectToAction("UploadFiles", "CIsAdmin") ;
}
if (check == false)
{
TempData["msg"] = "Successfull Upload";
Request.Files[upload].SaveAs(Path.Combine(path, filename));
return RedirectToAction("UploadFiles", "CIsAdmin");
}
}
}
return View("Upload");
}
Thanks in Advance
|
|
|
|
|
The difference between the Ajax and Submitting the form is that in Ajax , it is Async call and it does not reload your view. The ajax call receives the response from your action (URL) and does the update with the controls in the view based on your code.
Whereas in form submission , the action is called with post data and the view is reloaded again with action response.
So you have to check how you update the response message in your view based on these two different behaviours.
Hope this helps
|
|
|
|
|
Hi,
I got considerable gap in using front end tools like html or jquery etc, I am able to add options to my select by using jquery, what I want is, for each option I want to show remove button or image beside it, so that when user clicks on that image it will remove that option or delete that option. I tried to add using span or button or image but nothing worked so far, any help is going to be much helpful.
Thanks in advance my friends.
The way I am adding the options to select list is as below
$("#btnAddApplicationGroup").click(function (event) {
var $ddl = $("#ddlApplicationGroup"); //Getting the id of the dropdown
var $list = $("#lbxApplicationGroup"); // Getting the id of the listbox
var selValue = $ddl.val();
var selText = $ddl.find("option:selected").text();
if (($("#lbxApplicationGroup option[value='" + selValue + "']").length <= 0) && (selValue >= 1)) {
var $opt = $("<option></option>");
$opt.html(selText);
$opt.attr("value", selValue);
$list.append($opt);
}
});
$("#btnAddReportPack").click(function (event) {
var $ddl = $("#ddlReportPack"); //Getting the id of the dropdown
var $list = $("#lbxReportPack"); // Getting the id of the listbox
var selValue = $ddl.val();
var selText = $ddl.find("option:selected").text();
if (($("#lbxReportPack option[value='" + selValue + "']").length <= 0) && (selValue >= 1)) {
var $opt = $("<option></option>");
$opt.html(selText);
$opt.attr("value", selValue);
$list.append($opt);
}
});
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|