how to give textox dynamically at runtime in mvc4 bootstrap - asp.net-mvc

HI i am new to mvc and bootstrap.. i want to dynamically add two text box at run time in mvc4 and bootstrap.. i have tried many sites but i am not able to understand. please give me simple example
i have tried this
In model
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
in controller
public ActionResult PanelEx()
{
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
what should i wrote in model. how to do next step..i am stuck PLese help

public ActionResult PanelEx()
{
var initialData = new List<Gift>{
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
#model IEnumerable<Gift>
<div>
#foreach(var item in Model)
{
<div>
#Html.TextBoxFor(item=>item.Name)
</div>
}
</div>

Related

Placeholder on a #Html.Dropdownlist that is not selectable

How do i put a placeholder on my #Html.Dropdownlist that is not selectable.
I implemented chosen-jquery on my dropdown.
My code is as per below:
#Html.DropDownList("Id", new SelectList(new Ahib.Membership.UserFacade().GetAllUsers(), "Id", "Username"), "-select a system owner-", new { #class="chosen1-select" })
Currently my dropdownlist has a placeholder but the "-select a system owner-" becomes a selectable value which i dont want. How do solve this issue?
You can convert your list to the selectitem list and apply your disabled attribute from the controller itself.
like this
assuming your model is like this
class user
{
public int Id { get; set; }
public string Username { get; set; }
}
Convert your list to List<SelectListItem> like this, note here I am disabling the select a system owner entry.
public ActionResult Index()
{
List<user> users = new List<user>();
users.Add(new user { Id = 1, Username = "test1" });
users.Add(new user { Id = 2, Username = "test2" });
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-select a system owner-", Value = "0", Disabled = true });
foreach (var item in users)
{
list.Add(new SelectListItem
{
Text = item.Username,
Value = item.Id.ToString()
});
}
ViewBag.listItems = list;
return View();
}
and in view use it like this
#Html.DropDownList("test", ViewBag.listItems as IEnumerable<SelectListItem>);
Result:

Understanding how strongly typed html helper works

Framework: ASP.NET MVC 3
Tools: VS 2012
Hi guys,
I'm new to ASP.NET mvc, I have been using strongly typed html helper for some time,I don't understand them completely but know that it can provide type checking and keeps name according to property name,after using it for many times I faced this error constantly and dont seem to have any hint why its occuring tried several google searches but none helped me.
Error:
The name 'm' does not exist in the current context
Code:
#Html.LabelFor(m => m.OrginalCont.Title)
But this line of code works perfectly fine.
#Html.TextBox("origTitle", Model.OrginalCont.Title, new { #readonly = "", #class = "text-rounded", style = "width:425px" })
Can someone tell me whats going on here.I have used the same m => m.Name syntax several times in view but they are all working fine.
Update:
Alright I will try to post more code,but as the code may get too long I will try to keep it short and will post code which is related to the problem.
View
#model TS.MOP.Interface.Models.ProjectTranslationModel
<div class="form-item">
#Html.LabelFor(model => model.OrginalCont.Title)
<div class="editor-field">
#Html.TextBox("origTitle", Model.OrginalCont.Title, new { #readonly = "", #class = "text-rounded", style = "width:425px" })
</div>
</div>
Model
public class ProjectTranslationModel
{
public int ProjectId { get; set; }
[Required(ErrorMessageResourceType = typeof(Names), ErrorMessageResourceName = "Required_ErrorMessage")]
[DataType(DataType.Text)]
[Display(ResourceType = typeof(Names), Description = "TranslateLangs_Description", Name = "TranslateLangs_Title")]
public List<SelectListItem> TranslatableLangSelect { get; set; }
public TranslatableLanguageEditor TranslatableLangEditor { get; set; }
public OriginalContent OrginalCont { get; set; }
}
Controller
[Authorize]
public ActionResult TranslationEdit(int? id)
{
if (id.HasValue && User.IsInRole("ContentTranslator"))
{
var model = new ProjectTranslationModel();
model.ProjectId = id.Value;
var ContentTypeId = 2;//Project Page
Guid _currentUserId = Guid.Parse(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
var translatorSettings = db.TranslatorSettings.Where(x => x.UserId == _currentUserId).ToList();
model.TranslatableLangEditor = new TranslatableLanguageEditor();
var list = new List<SelectListItem>();
//Original Text
var originalContent = db.Projects.Where(x => x.Id == id.Value)
.Select(d => new OriginalContent { Title = d.Title, Content = d.Description, ContentCultureId = d.ProjectType.ContentCultureId }).FirstOrDefault();
model.OrginalCont = originalContent;
foreach (var item in translatorSettings)
{
//Select List
var li = new SelectListItem();
if (item.ContentCultureId != originalContent.ContentCultureId)//Dont add the Original Content CultureId to the dropDown
{
li.Value = item.ContentCultureId.ToString();
li.Text = item.ContentCulture.Description;
list.Add(li);
}
}
model.TranslatableLangSelect = list;
return View(model);
}
else
{
return View("Index");
}
}

Custom grid using Telerik pluggin in nopcommerce 2.8

Iam working on nopcommerce2.8 version. I have a problem with telerik plugin implementation to create new grid.
Iam implementing a concept where for a product i want to give different price for different customer. So to assign new price for different customers, in admin panel i am creating a grid in edit productvariant page using telerik. I have created a new tab to display these details. Iam able to display customer name and price in grid, but i am not able to call update function, when i click on update button after editing a row. The same update function i called for Deleting the grid row also, so when i click on delete the same update function getting trigger. I think some setting has been missed in View. Please help me to solve this update issue.
The model, view and controller of my nopcommerce in given below.
Thanks.
//Model
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using FluentValidation.Attributes;
using Nop.Admin.Models.Customers;
using Nop.Admin.Validators.Catalog;
using Nop.Web.Framework;
using Nop.Web.Framework.Localization;
using Nop.Web.Framework.Mvc;
using Telerik.Web.Mvc;
namespace Nop.Admin.Models.Catalog
{
public partial class CustomerProductPriceModel : BaseNopModel
{
public int Customer_Id { get; set; }
[NopResourceDisplayName("Customer Name")]
public string Customer_name { get; set; }
[NopResourceDisplayName("Price")]
public decimal Price { get; set; }
[NopResourceDisplayName("Unit")]
public string Units { get; set; }
}
}
// view
#(Html.Telerik().Grid<CustomerProductPriceModel>()
.Name("Grid")
.DataKeys(x =>
{
x.Add(y => y.Customer_Id);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("CustomerProductPriceList", "ProductVariant", new { productVariantId = Model.Id })
.Update("CustomerPriceUpdate", "ProductVariant", new { productVariantId = Model.Id })
.Delete("CustomerPriceUpdate", "ProductVariant", new { productVariantId = Model.Id });
})
.Columns(columns =>
{
columns.Bound(y => y.Customer_name).Width(200).ReadOnly();
columns.Bound(y => y.Price).Width(100);
columns.Command(commands =>
{
commands.Edit().Text(T("Admin.Common.Edit").Text);
commands.Delete().Text(T("Admin.Common.Delete").Text);
}).Width(180);
})
.Editable(x =>
{
x.Mode(GridEditMode.InLine);
})
.EnableCustomBinding(true)
)
// controller
[GridAction(EnableCustomBinding = true)]
public ActionResult CustomerPriceUpdate(GridCommand command, CustomerProductPriceModel model, int productVariantId)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
return AccessDeniedView();
return CustomerProductPriceList(command, productVariantId);
}
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult CustomerProductPriceList(GridCommand command, int productVariantId)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
return AccessDeniedView();
var productVariant = _productService.GetProductVariantById(productVariantId);
if (productVariant == null)
throw new ArgumentException("No product variant found with the specified id");
var CustomerPrices = PrepareCustomerProductPriceModel(productVariant.Product.Id);
var CustomerPricesa = CustomerPrices
.Select(x =>
{
return new CustomerProductPriceModel()
{
Customer_Id = x.Customer_Id,
Price = x.Price,
Units = x.Units,
Customer_name = x.Customer_name
};
})
.ToList();
var model = new GridModel<CustomerProductPriceModel>
{
Data = CustomerPricesa,
Total = CustomerPrices.Count
};
return new JsonResult
{
Data = model
};
}
Is there a reason not to use the built-in customer price levels already in place in nopCommerce, or are you wanting to display all prices at once?

.net mvc selectlist multiple sources

I have a list of users I am retrieving from Active Directory like so
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DOMAIN", "dc=domain,dc=org");
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, "Advisors");
ViewBag.EmployeeID = new SelectList(group.Members, "EmployeeID", "DisplayName");
I would like to add two additional items to this list but do not want to create user accounts for them in Active Directory as they are not real users.
Is it possible to do something like
var items1 = new[]
{
new { EmployeeID = "1", DisplayName = "Independent" },
new { EmployeeID = "2", DisplayName = "Own" }
};
var items = Concat(group.Members, items1);
{
ViewBag.EmployeeID = new SelectList(items, "EmployeeID", "DisplayName");
}
Well, You can have a ViewModel like this:
public class EmployeeViewModel
{
public string EmployeeId { get; set; }
public string DisplayName { get; set; }
}
and than you can cast the group.Members to a list of your ViewModel, add some custom itens on this list and set this list to the ViewBag.
var members = group.Members.Select(x => new EmployeeViewModel() { EmployeeId = x.EmployeeId, DisplayName = x.DisplayName }).ToList();
members.Add(new EmployeeViewModel() { EmployeeId = "1", DisplayName = "Independent" });
members.Add(new EmployeeViewModel() { EmployeeId = "2", DisplayName = "Own" });
ViewBag.EmployeeID = new SelectList(members, "EmployeeID", "DisplayName");

excel report not download, what need to do more?

Below code works well when I use a Submit button and put Excel export code in controller POST action.
Now I don't want post back and move the code like below, but now report is not download, although controller action "ExcelExport" called as expected, but report is not downloaded? Kindly suggest whats wrong here?
Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Decimal Price { get; set; }
public Product(int id, string name, string description, decimal price)
{
Id = id;
Name = name;
Description = description;
Price = price;
}
static readonly List<Product> AllProducts = new List<Product>
{
new Product(1, "Games Console", "Fun for all the family", 199.99m),
new Product(2, "MP3 player", "Listen to your favourite tunes on the move", 99.99m),
new Product(3, "Smart Phone", "Apps, apps, apps", 399.99m),
new Product(4, "Digital Photo frame", "All your photos in one beautiful frame", 49.99m),
new Product(5, "E-book reader", "Take your favourite books on the move with you", 149.99m),
new Product(6, "DVD Box Set", "All of season one plus exclusive extras", 39.99m)
};
public static List<Product> GetAllProducts()
{
return AllProducts;
}
Controller
public ActionResult Index()
{
return View();
}
public ActionResult ExcelExport()
{
var products = Product.GetAllProducts();
var grid = new GridView();
grid.DataSource = from p in products
select new
{
ProductName = p.Name,
SomeProductId = p.Id
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return Content("tr");
}
View
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
<div id="rptExport" style="display: none">
</div>
<input type="button" id="ExportExcelButton" value="Export To Excel" onclick="ExportExcel()" />
}
<script type="text/javascript">
//global cache false
$.ajaxSetup({ cache: false });
function ExportExcel() {
//block the UI until the request is rendered
$.blockUI({ message: '<h3><b><img src="#Url.Content("~/content/images/loading.gif")" />Please wait while Processing</b></h3>' });
$('#rptExport').load('#Url.Action("ExcelExport", "Home")', function (data) {
var urlFile = "";
if (data != '') {
debugger;
//unblock the UI
$.unblockUI();
}
});
}
You cannot use AJAX to download a file.
You need to use a regular page request.

Resources