MVC ViewBag with url removes all the symbols when view has loaded - asp.net-mvc-3

I'm trying to display/return a url using a viewbag. I get this on the Action as the value of the ViewBag:
http:\\www.mysite.com\\images\\logo.jpg
But whenever the view gets loaded all the slash gets removed and would end up with this:
http:wwwmysitecomimageslogo.jpg
EDIT: For Code on generating the LogoUrl.
EDIT 2: This is how I pull it out of the db, I use context and pull it out using EF, how else do you pull it out?
ViewBag.LogoUrl = context.Event.FirstOrDefault(e => e.Id == id).LogoUrl;
This is how I know what gets pulled:
string url = context.Event.FirstOrDefault(e => e.Id == id).LogoUrl;
ViewBag.LogoUrl = url;
This is how I use it:
var logoUrl;
$('#logo').click(function (event) {
<% if(ViewBag.LogoUrl != null) { %>
logoUrl = '<%: ViewBag.LogoUrl %>';
<% } %>
:
:
:
return false;
}
Make sense?

Related

Display Image using AJAX

I am trying to display a picture that I am calling from the controller using AJAX, this is my code:
<div id="productImg" style="display:none;">
</div>
<script>
function showPic(id) {
$.ajax({
type: "GET",
url: "/Equipment/GetImage",
data: { 'productId': id },
success: function (data) {
$("#productImg").html(data)
}
});
</script>
And the method on my controller looks like this:
public virtual FileContentResult GetImage(int productId) {
Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
What I am getting is a lot of code and not the image. What else could I try?
You don't need to use AJAX for this. Images are separate resources for a page and are loaded as separate requests already. Just link to it:
<div id="productImg">
<img src="/Equipment/GetImage?productId=123" alt="Product" />
</div>
For making that happen dynamically in JavaScript, all you need to do is change that src value:
function showPic(id) {
$('#productImg img').src = '/Equipment/GetImage?productId=' + id;
}
As an aside, the reason your approach doesn't work is because what you're getting back from the server isn't HTML, it's the raw image data. The HTML to display an image is not the image data itself, it's just an img tag with a URL. (That URL can contain an encoded copy of the actual data, but it really doesn't need to in this case.)
Please modify your Action method to something like this:
public virtual ActionResult GetImage(int productId)
{
Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null)
{
return new FileStreamResult(prod.ImageData, prod.ImageMimeType);
}
else
{
return null;
}
}
Let me know if this works...
Alternatively, what you can do is, you can prepend some text to the image data coming from the ajax call to display the image. All you have to do is, just prepend
data:image/png;base64,
where image/png is the mime-type.
Then when you push your src to the image tag the src will look something like this...
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" />
Hope it works...

how to display data using viewdata in asp.net mvc

Given below was my code, and when i am login in form at time error will occur is that " Object reference not set to an instance of an object. ".Actually i m display data in master page.
Master page:-
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<%# Import Namespace="ClientProj.Models" %>
<%foreach(var m in (IEnumerable<user_master>)ViewData["email"])
{ %>
<%=m.email %>
<%} %>
And My Controller :-
public ActionResult Index()
{
ViewData["email"] = from p in db.user_master select p;
return View();
}
[HttpPost]
public ActionResult Index(user_master log)
{
ViewData["email"] = from p in db.user_master where
p.user_id==Convert.ToInt32(Session["user"]) select p;
var ss = from p in db.user_master
where p.username == log.username &&
p.user_password == log.user_password
select p;
if (ss.Count() > 0)
{
Session["id"] = ss.First().user_id;
Session["user"] = ss.First().username;
return RedirectToAction("Home");
}
else
{
return RedirectToAction("index");
}
return View();
}
You're setting ViewData in your controller in one method, but trying to read it out in the master page for ANY page. This means you'll need to ensure that every action you have sets the Viewdata, which is really a bad idea.
What's probably happening here is that you've got another action which isn't setting the ViewData, such as the HttpPost version of Index.

call to controller to populate text box based on dropdownlistfor selection using Ajax

I have a dropdown and when I select an item from it, I want to pass on the selected value to a function in a controller, query the db and auto load a text box with query results.
How do I use Ajax to make that call to the controller when there is onclick() event on the dropdown?
My dropdown and textbox in my aspx page is:
<%: Html.DropDownListFor(model => model.ApplicationSegmentGuid, Model.ApplicationSegment)%>
<%: Html.TextAreaFor(model => model.EmailsSentTo, false, new { style = "width:500px; height:50px;" })%>
My function in controller is
public ActionResult AsyncFocalPoint(Nullable<Guid> ApplicationSegmentGuid)
{
string tempEmail = UnityHelper.Resolve<IUserDirectory>().EmailOf();
tempEmail = "subbulakshmi.kailasam#lyondellbasell.com" + tempEmail;
IList<string> EmailAddresses = new List<String>();
using (TSADRequestEntities context = UnityHelper.Resolve<TSADRequestEntities>())
{
EmailAddresses = context.FOCALPOINTs.Where(T => T.APPLICATIONSEGMENT.ItemGuid == ApplicationSegmentGuid && T.FlagActive)
.Select(T => T.Email).ToList();
}
foreach (string emailAddress in EmailAddresses)
tempEmail = tempEmail + ";" + emailAddress;
return Json(tempEmail, JsonRequestBehavior.AllowGet);
}
You could give your dropdown an id and url:
<%= Html.DropDownListFor(
model => model.ApplicationSegmentGuid,
Model.ApplicationSegment,
new { id = "myddl", data_url = Url.Action("AsyncFocalPoint") }
) %>
and then subscribe to the .change() event of the dropdown list unobtrusively and trigger the AJAX request:
$(function() {
$('#myddl').change(function() {
// get the selected value of the ddl
var value = $(this).val();
// get the url that the data-url attribute of the ddl
// is pointing to and which will be used to send the AJAX request to
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
data: { applicationSegmentGuid: value },
success: function(result) {
// TODO: do something with the result returned by the server here
// for example if you wanted to show the results in your textarea
// you could do this (it might be a good idea to override the id
// of the textarea as well the same way we did with the ddl):
$('#EmailsSentTo').val(result);
}
});
});
});

Linq MVC 2 TryUpdateModel nullable bool

I have been having an issue with updating a nullable bool value using TryUpdateModel. I have a template created to handle the values as so:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Boolean?>" %>
<% if (ViewData.ModelMetadata.IsNullableValueType) { %>
<%= Html.DropDownListFor(model => model, new SelectListItem[] { new SelectListItem() { Text = "", Value = "null"},new SelectListItem() { Text = "Yes", Value = "true"}, new SelectListItem() { Text = "No", Value = "false" }})%>
<% } else { %>
<%= Html.CheckBoxFor(model => model.Value)%>
<% } %>
My View looks like this:
<%=Html.EditorFor(model => model.TestField) %> //which looks/acts correctly
The SQL Server Database types are also defined correctly as a nullable bit.
My Code is straight forward:
var so = new SomeObject();
if (ModelState.IsValid)
{
//gets to here
if (TryUpdateModel(so))
{
//never gets here
}
}
The Error reported for ModelState on that field is: "The value 'null' is not valid for TestField."
This seems pretty straight forward, but I wasn't able to find anything on this. Any help would be greatly appreciated.
Cheers,
Brian
Since nobody has answered my question, I will put my workaround up. It's not super elegant, but it works. If I wanted it to be pretty, it'd be in a pink font. ;)
Basically I had to load "so" (someObject) manually using the form Collection like so...
var so = new SomeObject();
if (ModelState.IsValid)
{
so.WasItFound = StringToNullBool(form["WasItFound"]);
so.WhereWasItFound = form["WhereWasItFound"];
//fill in the rest of the properties using the form Collection...
}
private bool? StringToNullBool(string s)
{
if (s != "null")
return Convert.ToBoolean(s);
else
return null;
}

ASP.NET MVC 2: prevent ajax action link from replacing the updateTarget

I use an ajax action link on a view, then bind a js function onto its onCompleted property.
In this function, i get the response object, do some funny stuff, then write the message property to the updatetarget element.
The problem is, when it finishes its work on the oncompleted event, it writes the raw json response onto the updatetarget element, replacing the text i already written. I want to prevent it to write the raw response to the updatetarget. I'm aware of the InsertionMode property, but its useless to me because it appends text to the element one way or another.
The scripts i mentioned are below;
The code of the action link on view:
<%: Ajax.ActionLink("Delete", "Delete",
new { id = Model.Id, secretKey = Model.SecretKey },
new AjaxOptions { OnComplete = "WriteJsonResultToElement", UpdateTargetId="commandResult" })
%>
The WriteJsonResultToElement function
function WriteJsonResultToElement(resultObject) {
updateTarget = resultObject.get_updateTarget();
obj = resultObject.get_object();
$(updateTarget).text(obj.message); // here i set the text of update target
if (obj.result > 0)
$('*:contains("' + obj.id + '")').last().parent().remove();
}
My JsonResult Delete method returns this data after action:
{"message":"Deleted","result":1,"id":132}
Thanks.
If you don't want the raw JSON response appended to the DOM don't specify an UpdateTargetId:
<%: Ajax.ActionLink(
"Delete",
"Delete",
new { id = Model.Id, secretKey = Model.SecretKey },
new AjaxOptions { OnComplete = "success" })
%>
and handle it in the success callback:
function success(result) {
var obj = result.get_object();
alert(obj.message);
// TODO: do something with the object
}

Resources