Dropdowns not rendered when override object.cshtml MVC4 - asp.net-mvc-4

My actual problem was mentioned here.
Hide property of model in dynamic view
To solve the problem, I have overrided object.cshtml as mentioned in the answer.
However, when I did this, the dropdowns that I am rendering using UIHints are not working.
In place of dropdown, just False, False False (the no.of Falses are equal to number of list items I have in my viewdata) are displayed.
I am not sure what is happening here, can somebody advise what is going on?
in my controller:
ViewData["PartyRoleTypeId"] = (IEnumerable<SelectListItem>)PartyRoleTypeRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyRoleTypeId.ToString(), Text = p.Caption, Selected = p.PartyRoleTypeId == obj.PartyRoleTypeId });
ViewData["PartyId"] = (IEnumerable<SelectListItem>)PartyRepo.All()
.ToList()
.Select(p => new SelectListItem { Value = p.PartyId.ToString(), Text = p.Organization.Caption, Selected = p.PartyId == obj.PartyId });
My dropdown edit template in shared/editortemplates/DropDownList.cshtml
#{
var fieldName = ViewData.ModelMetadata.PropertyName;
}
#Html.DropDownList("",(IEnumerable<SelectListItem>)ViewData[fieldName], "Choose..." , new { #class ="combo"})
object.cshtml
#functions
{
bool ShouldShow (ModelMetadata metadata)
{
return metadata.ShowForEdit
&& metadata.ModelType != typeof(System.Data.EntityState)
&& !metadata.IsComplexType
&& !ViewData.TemplateInfo.Visited(metadata);
}
}
#if (ViewData.TemplateInfo.TemplateDepth > 1)
{
if (Model == null)
{
#ViewData.ModelMetadata.NullDisplayText
}
else
{
#ViewData.ModelMetadata.SimpleDisplayText
}
}
else
{
//ViewData.Clear();
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => ShouldShow(pm)))
{
if (prop.HideSurroundingHtml)
{
#Html.Editor(prop.PropertyName)
}
else if (prop.DisplayName == "Id")
{
<div></div>
}
else if (!string.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString()))
{
<div class="editor-label">#Html.Label(prop.PropertyName)</div>
}
<div class="editor-field">#Html.Editor(prop.PropertyName) #Html.ValidationMessage(prop.PropertyName, "")</div>
}
}

There is some problem with keeping my dropdown values in ViewData or ViewBag.
When I use these, for prartyroletypeid it is not recognizing UIHint dropdownlist.cshtml. It is still referring to object.cshtml.
Instead I kept the dropdown data in TempData and everything is working fine.
But not sure, if I can use TempData in this context.
Any ideas???

Related

Form data not updating after calling action with ajax

I have a table in my form and I don't want it to display until a link on the page is clicked which would call an action to get the data and redirect back to the same view so the table is populated. In essence like a master/detail form. I added a css class to hide the table but the only way I know of to call the action is to use ajax. I wrote the code for the function but and it seems to work fine but the table does not populate and I can't figure out why. I am using a partial view for the table which is supposed to be populated after the link is clicked. I'm very new to MVC so I have no idea what I'm missing, any help would be appreciated.
This is the link used in the jquery click event
<td><a id="viewOrder" href="#" data-PONumber-id=#osOrder.PurchaseOrderNumber>View Order</a></td>
This is my jQuery to call the action in the controller
$(document).ready(function() {
$("#viewOrder").on("click",
function(e) {
var button = $(this);
$.ajax({
type: "GET",
url: '#Url.Action("Details", "Receiving")',
data: { "id": button.attr("data-PONumber-id") },
success: function() {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
orderButton.addClass("visible");
}
});
});
});
This is my controller code.
public ActionResult Details(int id)
{
var purchaseOrder = _context.PurchaseOrders.Single(p => p.PurchaseOrderNumber == id);
var viewModel = new ReceivngFormViewModel
{
PO = purchaseOrder.PurchaseOrderNumber,
Vendor = purchaseOrder.Vendor.VendorName,
Contact = purchaseOrder.Vendor.Phone,
OutstandingOrders = _context.PurchaseOrders.Where(od =>
od.Closed == false && !String.IsNullOrEmpty(od.PurchaseOrderNumber.ToString()) &&
od.OrderDate != null).ToList(),
ReceivedOrderDetails = _context.PurchaseOrderDetails
.Where(pod => pod.PurchaseOrderID == purchaseOrder.PurchaseOrderID && (pod.Quantity - pod.ReceiveOrderDetails
.Sum(rod => rod.QuantityReceived)) != 0)
.Select(pod => new ReceivedOrderDetail
{
PurchaseOrderId = pod.PurchaseOrderID,
PurchaseOrderDetailId = pod.PurchaseOrderDetailID,
PartId = pod.PartID,
PartDescription = pod.Part.Description,
QtyOnOrder = pod.Quantity,
QtyOutstanding = pod.ReceiveOrderDetails.Select(rod => rod.QuantityReceived).Any() ?
pod.Quantity - pod.ReceiveOrderDetails.Sum(rod => rod.QuantityReceived) : pod.Quantity
}).ToList()
};
return View("Index", viewModel);
}

how to add an image to product in prestashop

i have a pragmatically added product in my code , the product is added to presta correctly but not about its image .
here is some part of my code that i used :
$url= "localhost\prestashop\admin7988\Hydrangeas.jpg" ;
$id_productt = $object->id;
$shops = Shop::getShops(true, null, true);
$image = new Image();
$image->id_product = $id_productt ;
$image->position = Image::getHighestPosition($id_productt) + 1 ;
$image->cover = true; // or false;echo($godyes[$dt][0]['image']);
if (($image->validateFields(false, true)) === true &&
($image->validateFieldsLang(false, true)) === true && $image->add())
{
$image->associateTo($shops);
if (! self::copyImg($id_productt, $image->id, $url, 'products', false))
{
$image->delete();
}
}
but my product have not any image yet
the problem is in copyImg method ...
here is my copyImg function :
function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
{
$tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
$watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
switch ($entity)
{
default:
case 'products':
$image_obj = new Image($id_image);
$path = $image_obj->getPathForCreation();
break;
case 'categories':
$path = _PS_CAT_IMG_DIR_.(int)$id_entity;
break;
}
$url = str_replace(' ' , '%20', trim($url));
// Evaluate the memory required to resize the image: if it's too much, you can't resize it.
if (!ImageManager::checkImageMemoryLimit($url))
return false;
// 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
// Just hide the warning, the traitment will be the same.
if (#copy($url, $tmpfile))
{
ImageManager::resize($tmpfile, $path.'.jpg');
$images_types = ImageType::getImagesTypes($entity);
foreach ($images_types as $image_type)
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'],
$image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
else
{
unlink($tmpfile);
return false;
}
unlink($tmpfile);
return true;
}
can anybody help me ?
You have 2 issues:
You are passing 5th parameter (with value) to copyImg, while the function does not have such.
Your foreach ($images_types as $image_type) loop must include the Hook as well (add open/close curly braces).
foreach ($images_types as $image_type)
{
ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
if (in_array($image_type['id_image_type'], $watermark_types))
Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
}
You should also check if the product is imported correctly, expecially the "link_rewrite" and if the image is phisically uploaded in the /img/ folder.

Html.DropDownListFor will ignore ViewBag values

I have the following action method:-
public ActionResult AdvanceSearch(string AssetTypeName)
{
ViewBag.Techtypes = repository.GetAllTechnologyType().ToList();
ViewBag.AssetID = repository.GetTechnologyTypeID(AssetTypeName);
return View();
}
which will call the folloiwng view :-
//code goes here
#Html.DropDownListFor(model =>model.AssetTypeID, ((IEnumerable<TMS.Models.TechnologyType>)ViewBag.Techtypes).Select(option => new SelectListItem {
Text = (option == null ? "None" :option.Name),
Value = option.AssetTypeID.ToString(),
Selected = (Model != null) && (option.AssetTypeID == ViewBag.AssetID)
}), "All")
//code goes here
but the drop down will always show the default value"All" , instead of selecting the item that match the viewBag value option.AssetTypeID == ViewBag.AssetID. baring in ming that the ViewBag will have the correct value. can anyone adice what might be the problem ?
Thanks
I think your condition is wrong. Try this. Check the 'Selected' property.
#Html.DropDownListFor(model => model.AssetTypeID, ((IEnumerable<TechnologyType>)ViewBag.Techtypes).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Name),
Value = option.AssetTypeID.ToString(),
Selected = (option.AssetTypeID == (int)ViewBag.AssetID)
}), "All")

Html.CheckBox not being set [asp.net mvc 4]

I am having a bit of a headache with a thing (I know something like has been asked before, but I'm pretty sure it's not quite the same thing).
To the point:
I have a View with a Telerik grid. On that grid I show some stuff from the model that I pass to the View BUT I want in the final column to put a CheckBox that is checked/unchecked based on some things in the Controller (the checks have nothing to do with the model that is being passed). In my ActionResult function that takes care of the View I store some Boolean values in the ViewData, and then I set the isChecked value in the CheckBox based on the values stored in the ViewData.
The code for the ActionResult is as follows:
[SecureThis(Roles = "User")]
public ActionResult Index()
{
//get bucket ids
var buckets = db.Buckets.ToList();
int i=1;
string cb = "checkbox" + i.ToString();
foreach (Bucket b in buckets)
{
var payByInvoice = db.PaymentOptions.Where(p => p.BucketId == b.Id).Select(p => p.CanPayByInvoice).SingleOrDefault();
if (payByInvoice == (int)PayByInvoiceState.Accepted)
ViewData["checkbox" + i.ToString()] = true;
else ViewData["checkbox" + i.ToString()] = false;
i++;
cb = "checkbox" + i.ToString();
}
return View(db.Buckets);
}
And the grid that should show all the stuff is this:
#{
int i=1;
string cb = "checkbox" + i.ToString();
}
#(Html.Telerik().Grid(Model)
.Name("BucketsGrid")
.DataKeys(keys => keys.Add(bucket => bucket.Id))
.Columns(
columns =>
{
columns.Template(model => ViewData[model.Id.ToString()])
.HeaderTemplate(
#<b>#Strings.Title_Customer</b>
);
columns.Bound(model => model.CreditFacility);
columns.Bound(model => model.Minimum);
columns.Bound(model => model.RefillLevel);
columns.Bound(model => model.NotificationEmail);
columns.Bound(model => model.NotificationSms);
columns.Template(model => Html.ActionLink(Strings.Edit, "Edit", new { id = model.Id }));
columns.Template(model => Html.ActionLink(Strings.NotificationOptions, "Bucket", "NotificationOptions", new { id = model.Id }, null));
columns.Template(model => Html.ActionLink("Refill", "Refill", "Payment", new { id = model.Id }, null));
columns.Template(model => Html.ActionLink(Strings.Details, "Details", new { id = model.Id }));
columns.Template(model => Html.ActionLink(Strings.Delete, "Delete", new { id = model.Id }));
columns.Template(model => Html.CheckBox("invoice", (Boolean)ViewData[#cb])).HeaderTemplate("Invoice Option");
#i++;
#cb = "checkbox" + i.ToString();
}
)
.Pageable(paging =>
paging.Enabled(true)
.PageSize(UserSettings.GridPageSize)
.Style(GridPagerStyles.NextPrevious)
.Position(GridPagerPosition.Bottom)
)
.Sortable()
.Scrollable()
.Resizable(resize=> resize.Columns(true))
)
The problem with this whole thing is that the checkboxes remain unchecked, no matter the data stored in the ViewData. I went with the debugger and the values are se accordingly in the ViewData, but for some reason (that I cannot yet tell) the checkboxes still remain unchcked.
Any ideas on this matter would be much appreciated.
I have found out the problem of all this. As expected, it was my own doing (or so to say). The problem was that I incremented the #i variable inside the Telerik grid declaration, thinking that it would happen for all the rows in the grid, but that thing is only triggered once. Hence, the ViewData[#cb] value would always have the 2nd value set in the Controller (which in my case was false) and all the checkboxes would then be unchecked.
The fix:
I used the ViewBag and set it up with a Dictionary<Guid, bool> to hold my values, and iterate through it using the model.Id property. For anyone who might be interested I'll post the code below.
Controller:
ViewBag.Dict = new Dictionary<Guid, bool>();
Dictionary<Guid, bool> dict = new Dictionary<Guid, bool>();
foreach (Bucket b in buckets)
{
var payByInvoice = db.PaymentOptions.Where(p => p.BucketId == b.Id).Select(p => p.CanPayByInvoice).SingleOrDefault();
if (payByInvoice != (int)PayByInvoiceState.Accepted)
{
dict.Add(b.Id, false);
}
if (payByInvoice == (int)PayByInvoiceState.Accepted)
{
dict.Add(b.Id, true);
}
}
ViewBag.Dict = dict;
View:
columns.Template(model => Html.CheckBox("invoice", (bool)ViewBag.Dict[model.Id])).HeaderTemplate("Invoice option");

How do I know which element is modifying in contentEditable case?

I have a little problem / question. I work on a little WYSIWYG editor. I use a div with the option contentEditable="true" and I would like to know when there is a click on a button which element in my div is modifying by the user.
For example if there is 3 paragraphs on the the div, and that user modifies the second, I would like to know when he clicks on a button that he is currently to modify the second paragraph to show the text content ! In this example "P2" :
<div contenteditable="true"><p>P1</p><p>P2</p><p>P3</p></div>
Thanks in advance for your help.
Nicolas
You could examine the selection in the mousedown event of the button. The following will work in all major browsers:
function getSelectionBoundaryContainerElement(start) {
var container = null;
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0);
range.collapse(start);
container = range.startContainer;
if (container.nodeType != 1) {
container = container.parentNode;
}
}
} else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
var textRange = document.selection.createRange();
textRange.collapse(start);
container = textRange.parentElement();
}
return container;
}
document.getElementById("yourButtonId").onmousedown = function() {
alert(getSelectionBoundaryContainerElement().innerHTML);
}