Retrieve object from URL in mvc - asp.net-mvc

This is for a school project, and I don't really understand exactly what I'm supposed to do, so I'll explain what the teacher told me and what I did so far, hope you guys can help.
To examine the success of a program, the teacher wants to manually add a number to the url of the page.
I need to take that number, extract it from the url, then implant it in a method so that it will decrypt a message with the same ID number (I have no idea how he intends to do it or activate said method).
Here is what I wrote:
In the DataModel:
public static void GetMessage (int? MesNum, out string MesSuc)
{
SqlConnection cnctn = new SqlConnection(cnctnstrng);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cnctn;
cmd.CommandText = "GetMessage";
cmd.Parameters.Add("#LineNum", SqlDbType.Int);
SqlDataReader rd;
try
{
cnctn.Open();
cmd.Parameters["#LineNum"].Value = MesNum;
rd = cmd.ExecuteReader();
byte[] Message = (byte[])rd["MessageText"];
if (Message != null)
{
MesSuc = chat.Models.DomainModels.Security.DecryptStringFromBytes(Message);
}
else
{
MesSuc = "Unable to decrypt Message";
}
}
catch
{
MesSuc = "Unable to decrypt Message";
}
finally
{
cnctn.Close();
}
}
In the Controller:
public ActionResult singlmsgdecrptn()
{
string MesSuc;
chat.Models.DataModels.userdbmanip.GetMessage(*?*, out MesSuc);
return View(MesSuc);
}
The ? is where the number is supposed to come in.
In the View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>singlmsgdecrptn</title>
</head>
<body>
<div>
#ViewBag.MesSuc
</div>
</body>
</html>

The default routing for MVC takes and ID optional parameter. Check the RouteConfig.cs in the App_Start folder.
So you should just be able to add it as a parameter to your controllers action result.
public ActionResult singlmsgdecrptn(int? id)
{
string MesSuc;
chat.Models.DataModels.userdbmanip.GetMessage(id, out MesSuc);
return View(MesSuc);
}
Also, not sure why you're using a nullable int here, but I followed suit. Hope this helps, good luck.

Related

Active Directory how to get user from distinguishedName

I need some help on retrieving a user with distinguishedName in asp.net mvc project. I have a search function that has 2 properties to load, "displayName" and "distinguishedName". Once I find, I return a view with a list containing these two parameters for each user found. Then I want to be able to click on a user and immediately show their information. So how do I load the information about the user once I only have these two parameters passed through?
Here is the function that initially searches:
public List<string> SearchUserByName(string name){
try{
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("distinguishedName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
if (sResult.Properties["distinguishedName"][0].Equals(null) ||
sResult.Properties["displayName"][0].Equals(null))
continue;
displayName.Add(sResult.Properties["distinguishedName"][0].ToString());
displayName.Add(sResult.Properties["displayName"][0].ToString());
}
}
ldapConnection.Close();
ldapConnection.Dispose();
search.Dispose();
return displayName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
Now my view:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Résultat de recherche d'utilisateurs</title>
</head>
<body>
<h2> Résultat de recherche d'utilisateurs</h2>
#{
var incLoop = 0;
var incArr = 0;
var list = (List<string>)ViewData["Names"];
var size = list.Count();
string[] objSID = new string[size];
foreach (var link in list)
{
if (incLoop % 2 == 0)
{
objSID[incArr] = link;
incArr++;
}
else
{
#link<br/>
}
incLoop++;
}
}
</body>
</html>
If you click on #link in the tag, you get the information, which is shown in the next view. I've also split my list to not show the distinguishedName in the search result view.
What I have done for now, is researching the Active Directory when you click on the link, but it seems like bad practice (searching twice for one result). Any ideas?
Thank you, hope it's clear

Controller returned data not binding to image in asp.net MVC

I want to get image from database and display it in the view. image is retrieved but from database but not binding to image. This is my controller code
public ActionResult GetSignatureDetails()
{
byte[] image = (from m in objIycEntity.Signatures
where m.SignatureID == 5
select m.Signature1).FirstOrDefault();
var stream = new MemoryStream(image.ToArray());
return new FileContentResult(image, "image/jpeg");
}
And this is my view
<img src='#Url.Action("GetSignatureDetails","Agent")' />
But always image src in firebug is src="/Agent/GetSignatureDetails"
Please can any one help me what I am doing wrong
I give you a sample code hope this will help you:
View :
#model MvcApplication2.Models.AgentProfile
#{
ViewBag.Title = "imageDemo";
}
<h2>imageDemo</h2>
<img width="100" height="80" src="/Profile/ShowImage/2" alt="" />
And Controller Code Like this:
public ActionResult ShowImage(int id)
{
if (id>0)
{
AgentProfile objag = new AgentProfile();
MvcApplication2.Models.Image obj = new MvcApplication2.Models.Image();
obj.ImageID = id;
DataSet ds = obj.SelectImage();
objag.ImageSource = (byte[])ds.Tables[0].Rows[0]["ImageContent"];
//objag.ImageSource = (byte[])row["ImageContent"];
return File(objag.ImageSource, "image/jpg");
}
else
{
return RedirectToAction("Index");
}
}
Thanks.
have you tried it this way?
public FileContentResult GetSignatureDetails()
{
byte[] image = (from m in objIycEntity.Signatures
where m.SignatureID == 5
select m.Signature1).FirstOrDefault();
return File(image, "image/jpeg");
}

Caching in asp.net MVC4

I'm trying to update my web page's time every 3 seconds. this is how how i'm trying to do it:
[OutputCache(Duration = 3)]
public ActionResult Index()
{
ViewBag.Message = "Time : " + DateTime.Now;
return View();
}
but it does't refresh the page. Can someone please give me an idea how to solve this. thank you in advance!
You can Achieve it by using java script in asp form.
<p id="demo"></p>
<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
You also may use the meta tag for refreshing the page if it's ok to hit the server as below,
<meta http-equiv="refresh" content="3;">

Not receiving JSONP callback

I am following the sample code/tutorial for ASP.NET MVC and JSONP blog post: http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
I have taken the code sample and have modified it for my own consumption.
When I hit the page, it fires off my controller's action but the $.getJSON(call, function (rsp).. is not firing at all.
Controller action
[JsonpFilter]
public JsonpResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
HTML Page
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var url = "http://localhost/MySite.ContentDelivery/MyController/GetMyObjects/?";
function getObjects() {
//
// build the URL
//
debugger;
var call = url + "id=48&jsoncallback=?";
//
// make the ajax call
//
$.getJSON(call, function (rsp) {
debugger;
alert(rsp);
if (rsp.stat != "ok") {
//
// something went wrong!
//
$("#myDiv").append(
"<label style=\"background-color:red;color:white;padding: 25px;\">Whoops! It didn't work!" +
" This is embarrassing! Here's what the system had to " +
" say about this - " + rsp.message + "</label>");
}
else {
//
// build the html
//
var html = "";
$.each(rsp.list.myObject, function () {
var obj = this;
html += "<span" + obj.Name + "</span> <br />";
});
//
// append this to the div
//
$("#myDiv").append(html);
}
});
}
//
// get the offers
//
$(document).ready(function() {
alert('go..');
$(getOobjects);
});
</script>
<div id="myDiv"></div>
</body>
</html>
tl;dr why is my getJson() not firing while my getObjects() fires and executes the MVC controller action.
Replace:
var call = url + "id=48&jsoncallback=?";
with:
var call = url + "id=48&callback=?";
The custom JsonpResult you are using relies on a query string parameter called callback and not jsoncallback:
Callback = context.HttpContext.Request.QueryString["callback"];
Also you have decorated your controller action with a [JsonpFilter] attribute and returning a JsonpResult. As explained in the article you must have read you should choose one:
[JsonpFilter]
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return Json(list, JsonRequestBehavior.AllowGet);
}
or the other:
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
but do not mix the two.

How do I prevent IE save file dialog when using fileupload in asp.net mvc

When I try and upload a file using ASP.NET MVC it works fine in FF && Chrome, but in IE and Opera a dialog pops-up which asks me to either download, save or cancel.
Choosing either of the options, prevents the fileupload from working. How can I get round this problem?
public class ImportModel
{
[Required]
[FileExtensions("csv", ErrorMessage = "Please upload a valid .csv file")]
public HttpPostedFileBase File { get; set; }
}
[HttpPost]
public virtual ActionResult StartImport(ImportModel model = null)
{
if (model != null)
{
var status = _importService.StartImport(model);
return Json(status, JsonRequestBehavior.AllowGet);
}
return null;
}
View code below (summarised):
<div id="dlgImport" class="hidden">
#using (Html.BeginForm(MVC.Import.StartImport(), FormMethod.Post, new { #class = "smallForm", id = "frmImport", enctype = "multipart/form-data" }))
{
<div class="fields-inline">
<div class="editor-label">
#Html.Label("File")
</div>
<div class="editor-field">
#Html.TextBoxFor(x => x.File, new { #class="input-file", type = "file" })
#Html.ValidationMessageFor(x => x.File)
</div>
</div>
}
</div>
</div>
$(function() {
$("#frmImport").ajaxForm({
success: function (responseHtml) {
// response is wrapped in pre tags by the browser - the ajax upload is carried out using an iframe
var response = $.parseJSON($(responseHtml).text());
}
});
});
var vm = {
startImport: function () {
if ($("#frmImport").valid()) {
$("#frmImport").submit();
}
}
}
Now that you have posted your code it looks like that you are using the jquery form plugin. As explained in the documentation this plugin supports file uploads using AJAX but you cannot return JSON from your server side script:
Since it is not possible to upload files using the browser's
XMLHttpRequest object, the Form Plugin uses a hidden iframe element to
help with the task. This is a common technique, but it has inherent
limitations. The iframe element is used as the target of the form's
submit operation which means that the server response is written to
the iframe. This is fine if the response type is HTML or XML, but
doesn't work as well if the response type is script or JSON, both of
which often contain characters that need to be repesented using entity
references when found in HTML markup.
To account for the challenges of script and JSON responses, the Form
Plugin allows these responses to be embedded in a textarea element and
it is recommended that you do so for these response types when used in
conjuction with file uploads. Please note, however, that if there is
no file input in the form then the request uses normal XHR to submit
the form (not an iframe). This puts the burden on your server code to
know when to use a textarea and when not to.
So basically your upload controller action should respond with:
<textarea>{"foo":"bar"}</textarea>
instead of:
{"foo":"bar"}
Also you should not use the application/json response content type in this case.
You could write a custom action result to achieve that:
public class FileJsonResult : JsonResult
{
public FileJsonResult(object data)
: base()
{
Data = data;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("<textarea>");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea>");
context.HttpContext.Response.ContentType = "text/html";
}
}
and then:
[HttpPost]
public virtual ActionResult StartImport(ImportModel model = null)
{
if (model != null)
{
var status = _importService.StartImport(model);
return new FileJsonResult(status);
}
new FileJsonResult(new { status = false, errorMessage = "The model was null" });
}
Now you might also need to adapt your success handler to strip the <textarea> tags:
$('#frmImport').ajaxForm({
success: function (responseHtml) {
var responseHtml = responseHtml
.replace(/\<textarea\>/i, '')
.replace(/\<\/textarea\>/i, '');
var response = $.parseJSON(responseHtml);
// do something with the response
}
});
I had the same problem with IE8 and this answer helped me a lot. But I needed to make some changes that worked very well in IE8, Chrome and Firefox.
Follow changes below:
success: function (responseText) {
try{
var response = $.parseJSON(responseText);
//code ...
}
catch(ex) {
//error code
}
}
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file) {
//code
return Json(new { Success = "true", Message = "Done!" }, "text/html");
}

Resources