Cannot autocomplete textbox (search) - c#

I want to implement an autocomplete textbox, like the one in this tutorial: Implement autocomplete textbox functionally, but I can't make it work.
Controllers:
public ActionResult Productos(string searchString, string currentFilter, int? page)
{
int pageSize = 8;
int pageNumber = (page ?? 1);
ViewBag.CurrentFilter = searchString;
if (!String.IsNullOrEmpty(searchString))
{
var producto = db.ProductosList
.Where(m => m.Nombre.StartsWith(searchString))
.Include(x => x.Subcategoria)
.Include(x => x.Subcategoria.Categorias)
.Include(x => x.Subcategoria.Categorias.Marcas)
.OrderBy(x => x.Subcategoria.Nombre).ToPagedList(pageNumber, pageSize);
var subcategorias = db.SubcategoriasList
.Include(x => x.Categorias)
.OrderBy(x => x.Categorias.Nombre).ToPagedList(pageNumber, pageSize);
var categorias = db.CategoriasList
.Include(x => x.Subcategoriases)
.OrderBy(x => x.Subcategoriases.Count).ToPagedList(pageNumber, pageSize);
var model = new PagedListViewModel
{
SubcategoriasListes = subcategorias,
CategoriasListes = categorias,
ProductosListes = producto
};
ViewBag.Count = db.ProductosList.Count();
return View(model);
}
else
{
var producto = db.ProductosList
.Include(i => i.FilePaths)
.Include(x => x.Subcategoria)
.Include(x => x.Subcategoria.Categorias)
.Include(x => x.Subcategoria.Categorias.Marcas)
.OrderBy(x => x.Subcategoria.Nombre).ToPagedList(pageNumber, pageSize);
var subcategorias = db.SubcategoriasList
.Include(x => x.Categorias)
.OrderBy(x => x.Categorias.Nombre).ToPagedList(pageNumber, pageSize);
var categorias = db.CategoriasList
.Include(x => x.Subcategoriases)
.OrderBy(x => x.Subcategoriases.Count).ToPagedList(pageNumber, pageSize);
var model = new PagedListViewModel
{
SubcategoriasListes = subcategorias,
CategoriasListes = categorias,
ProductosListes = producto
};
ViewBag.Count = db.ProductosList.Count();
return View(model);
}
}
public JsonResult GetProductos(string search, int? page)
{
int pageSize = 8;
int pageNumber = (page ?? 1);
var producto = db.ProductosList
.Where(m => m.Nombre.StartsWith(search))
.Select(m => m.Nombre).ToList();
return Json(producto, JsonRequestBehavior.AllowGet);
}
View:
<link href="~/Content/Main/dis/dis/css/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Main/dis/dis/js/jquery-ui.js"></script>
<script src="~/Content/Main/dis/dis/js/jquery-ui.min.js"></script>
<script src="~/Content/Main/dis/dis/js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$("search").autocomplete({
source: '#Url.Action("GetProductos")'
});
});
</script>
<section class="page-title">
<div class="alert-style">
#{ Html.RenderPartial("_Alerts"); }
</div>
<div class="grid-row clearfix">
<h1>Productos</h1>
<br />
#using (Html.BeginForm("Productos", "Productos", FormMethod.Get))
{
<div class="input-group pull-right">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<p class="s"> #Html.TextBox("searchString", ViewBag.CurrentFilter as string, new { #id = "search", #placeholder = "¿Qué producto buscas?", autofocus = "autofocus" })</p>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<input type="submit" value="Buscar por producto" class="btn pull-left" id="busqueda" autofocus />
</div>
</div>
}
My code doesn't have any trouble executing, but it doesn't work.

Try this its working for me
$("#search").autocomplete({
minLength: 3,
source: '#Url.Action("GetProductos")',
select: function (event, ui) {
$('#search').val(ui.item.value);
},
change: function (event, ui) {
}
});
And In controller
public JsonResult GetProductos(string term)
{
var producto = db.ProductosList
.Where(m => m.Nombre.StartsWith(search))
.Select(m => m.Nombre).ToList();
return Json(producto, JsonRequestBehavior.AllowGet);
}

Your jquery selector is missing the hash character - it should be $("#search").autocomplete({... (like in Snehal's example).
Just as a side note you've got two references to jquery UI javascript - one minified and one not.
Hope this helps.

Related

my search button goes to the wrong function

My Get function works fine and the search textbox shows but when I enter the user ID and click search, it goes directly to the post function. It is supposed to go to the Get function again to show the data . after the data shows and whether I selected from the checkboxes or not, I click save and then it is supposed to go to the POst function.
What am I doing wrong?
GET function :
[HttpGet]
public ActionResult Index(int? SearchId)
{
var viewModel = new UserViewModel();
if (SearchId != null)
{
var userDepartments = db.TBL_User_Dep_Access.Where(x => x.UserID == SearchId).Select(x => x.Dep_ID).ToList();
List<UserDepartmentViewModel> udeptVM = db.TBL_Department.Select(i => new UserDepartmentViewModel
{
Dep_Id = i.Department_ID,
Dep_Name = i.Department_Name,
IsChecked_ = userDepartments.Contains(i.Department_ID)
}).ToList();
var userPermissions = db.TBL_UserPermissions.Where(x => x.UserID == SearchId).Select(m => m.PermissionID).ToList();
List<UsrPERViewModel> upVM = db.TBL_Permissions.Select(i => new UsrPERViewModel
{
Id = i.PermissionID,
Name = i.PermissionName,
IsChecked = userPermissions.Contains(i.PermissionID)
}).ToList();
viewModel.Departments = udeptVM;
viewModel.Permissions = upVM;
}
return View(viewModel);
}
My View:
#model Staff_Requisition.Models.UserViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<style>
.list-group {
max-height: 300px;
margin-bottom: 10px;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
</style>
#using (Html.BeginForm("Index", "TBL_UserPermission"))
{
#Html.AntiForgeryToken()
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="title_right">
<div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search">
<div class="input-group">
#Html.TextBox("SearchId", "", null, new { #id = "SearchId", #placeholder = "Search for...", #class = "form-control" })
<span class="input-group-btn">
<input class="btn btn-default" value="Search" type="submit">Go! />
</span>
<ul>
#if (Model.Permissions != null)
{
foreach (var P in Model.Permissions)
{
<li>
<p>
#Html.CheckBoxFor(modelItem => P.IsChecked, new { #class = "flat", #value = P.IsChecked })
#Html.DisplayFor(modelItem => P.Name, new { #class = "DepartmentName", #value = P.Name })
#Html.HiddenFor(modelItem => P.Id, new { #class = "Dep_Id", #value = P.Id })
</p>
</li>
}
}
</ul>
<ul class="to_do">
#if (Model.Departments != null)
{
foreach (var D in Model.Departments)
{
<li>
<p>
#Html.CheckBoxFor(modelItem => D.IsChecked_, new { #class = "flat", #value = D.IsChecked_ })
#Html.DisplayFor(modelItem => D.Dep_Name, new { #class = "DepartmentName", #value = D.Dep_Name })
#Html.HiddenFor(modelItem => D.Dep_Id, new { #class = "Dep_Id", #value = D.Dep_Id })
</p>
</li>
}
}
</ul>
<div class="col-xs-12 col-sm-6 emphasis">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</body>
}
My POST function:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserViewModel user_Pers)
{
//remove user with specified ID from database
db.TBL_UserPermissions.RemoveRange(db.TBL_UserPermissions.Where(c => c.UserID == user_Pers.SearchId));
db.TBL_User_Dep_Access.RemoveRange(db.TBL_User_Dep_Access.Where(c => c.UserID == user_Pers.SearchId));
//for each permission that's checked add user to the table
foreach (var u in user_Pers.Permissions)
{
if (u.IsChecked)
{
TBL_UserPermissions Tup = new TBL_UserPermissions();
Tup.UserID = user_Pers.SearchId;
Tup.PermissionID = u.Id;
Tup.IsActive = true;
db.TBL_UserPermissions.Add(Tup);
}
}
db.SaveChanges();
foreach (var d in user_Pers.Departments)
{
if (d.IsChecked_)
{
TBL_User_Dep_Access Tud = new TBL_User_Dep_Access();
Tud.UserID = user_Pers.SearchId;
Tud.Dep_ID = d.Dep_Id;
Tud.IsActive = true;
db.TBL_User_Dep_Access.Add(Tud);
}
}
db.SaveChanges();
return RedirectToAction("myInfo");
}
BTW I removed most of the div in the view manually for simplicity, so it's okay if an opening or closing doesn't match.
As has been pointed out in the comments, in your code you have 1 form whereas to solve the problem you are talking about you need 2 forms. One form responsible for the search get request and the other responsible for the user post.
Here is a simple example of a search form and an update form on the same page.
The viewmodel and controller
using System.Web.Mvc;
namespace SearchAndSubmit.Controllers
{
public class UserViewModel
{
public int? Id { get; set; }
public string Name { get; set; }
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Edit(int? SearchId)
{
var viewModel = new UserViewModel();
if (SearchId != null)
{
viewModel.Id = SearchId;
//logic to search for user and create viewmodel goes here
}
return View(viewModel);
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Edit(UserViewModel user_Pers)
{
//validation and create update logic goes here
return RedirectToAction("Index");
}
}
}
The view
#model SearchAndSubmit.Controllers.UserViewModel
#{
ViewBag.Title = "Edit/create user";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.Title</h2>
#*This is the search form it does a get request*#
#using (Html.BeginForm("edit", "home", FormMethod.Get))
{
#Html.TextBox("SearchId", "", null, new { #id = "SearchId", #placeholder = "Search for...", #class = "form-control" })
<span>
<input value="Search" type="submit">
</span>
}
#*This is the form for updating the user it does a post*#
#using (Html.BeginForm("edit", "home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(c => c.Id)
<p>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name)
</p>
<div>
<input type="submit" value="Save" />
</div>
}

NopCommerce - Page Navigation Issue with Telerik-Grid

I am using nopCommerce. I have used telerik-grid to bind data in a table and data binded successfully. I have create method named "EditContact" for Edit operation. but when i clicked Edit link to redirect page named "_CreateOrUpdateContact.cshtml", i got "Page not found" page.
telerik-grid code :
#(Html.Telerik().Grid<AddressModel>()
.Name("vendors-grid")
.Columns(columns =>
{
columns.Bound(x => x.CountryName)
.Width(200).Centered();
columns.Bound(x => x.FirstName)
.Width(200).Centered();
columns.Bound(x => x.LastName)
.Width(200).Centered();
columns.Bound(x => x.Title)
.Width(200).Centered();
columns.Bound(x => x.Email)
.Width(200).Centered();
columns.Bound(x => x.PhoneNumber)
.Width(200).Centered();
columns.Bound(x => x.Address1)
.Width(200).Centered();
columns.Bound(x => x.Id)
.Width(200)
.Centered()
.Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Edit").Text + "")
.Title(T("Admin.Common.Edit").Text);
columns.Bound(x => x.Id)
.Template(x => Html.ActionLink(T("Admin.Common.Delete").Text, "Delete", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Delete").Text + "")
.Centered().Width(200)
.HeaderTemplate(T("Admin.Common.Delete").Text);
})
.Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
.DataBinding(dataBinding => dataBinding.Ajax().Select("ListContacts", "VendorDetails",new { vendorId = Model.Id }))
.EnableCustomBinding(true))
EditContact.cshtml Code:
#model AddressModel
#using (Html.BeginForm())
{
<div class="section-header">
<div class="options">
<input type="submit" name="save" class="t-button" value="#T("Admin.Common.Save")" />
<input type="submit" name="save-continue" class="t-button" value="#T("Admin.Common.SaveContinue")" />
</div>
</div>
#Html.Partial("_CreateOrUpdateContact", Model)
}
#Html.DeleteConfirmation("vendor-delete")
VendorDetailsController Methods:
[HttpPost, GridAction(EnableCustomBinding = true)]
public ActionResult ListContacts(int vendorId,GridCommand command)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageVendors))
return AccessDeniedView();
var Addresses = _addressService.GetVendorAddresses(vendorId);
var gridModel = new GridModel<AddressModel>
{
Data = Addresses.Select(x =>
{
var a = new AddressModel();
PrepareAddressModel(a, x, false);
return a;
}),
Total = Addresses.Count,
};
return new JsonResult
{
Data = gridModel
};
}
// edit vendor contact
public ActionResult EditContact(int id)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageVendors))
return AccessDeniedView();
var address = _addressService.GetAddressById(id);
int vendorId = _vendorContactService.GetVendorIdByAddressId(address.Id);
if (address == null)
//No Address found
return RedirectToAction("Edit", new { id = vendorId });
var model = new AddressModel();
model.VendorId = vendorId;
//Ordering Method
model.AvailableCountries.Add(new SelectListItem() { Text = "-- Select --", Value = "0" });
foreach (var c in _countryService.GetAllCountries(true))
model.AvailableCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() });
PrepareAddressModel(model, address, false);
return View(model);
}
Am i doing something wrong?
How can i redirect from telerik grid- Edit Link to _CreateOrUpdateContact.cshtml page?
Please, check if "_CreateOrUpdateContact.cshtml" is in the same location with "EditContact.cshtml". I will suggest you to debug the code. Put a breakpoint at "public ActionResult EditContact(int id)" then check if debug point is hit after clicking the edit link from grid. If it is not hit then there may be some problem in route.
It would be better if you can provide the screen shot of the error you found
you can check the route here in the telerik-grid
columns.Bound(x => x.Id)
.Width(200)
.Centered()
.Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Edit").Text + "")
.Title(T("Admin.Common.Edit").Text);
as I think the route had a problem I should be like that
columns.Bound(x => x.Id)
.Width(200)
.Centered()
.Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "EditContact", new { id = x.Id }))
.ClientTemplate("" + T("Admin.Common.Edit").Text + "")
.Title(T("Admin.Common.Edit").Text);

MVC 4 Validation with a partial view

I'm using MVC 4 and Entity Framework to develop a web app. I'm working with partial views which are loaded with javascript. One of them is a create view which includes validation. And that's my problem : the validation. I have a custom validation logic and, for example, if a user enters some numbers into a field such as "Name", it displays an error.
Here, with the partial views, it redirects me on my partial with the errors displayed but what I wanted to do is to stay on my main view (Index view) and keep my partial view which displays the errors.
EDIT :
Here is my partial view :
#model BuSIMaterial.Models.Person
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
First name :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
Last name :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
National number :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.NumNat, new { maxlength = 11 })
#Html.ValidationMessageFor(model => model.NumNat)
</div>
<div class="editor-label">
Start date :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.StartDate, new {#class = "datepicker", #placeholder="yyyy/mm/dd"})
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
End date :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.EndDate, new { #class = "datepicker", #placeholder = "yyyy/mm/dd" })
#Html.ValidationMessageFor(model => model.EndDate)
</div>
<div class="editor-label">
Distance House - Work (km) :
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HouseToWorkKilometers)
#Html.ValidationMessageFor(model => model.HouseToWorkKilometers)
</div>
<div class="editor-label">
Category :
</div>
<div class="editor-field">
#Html.DropDownList("Id_ProductPackageCategory", "Choose one ...")
#Html.ValidationMessageFor(model => model.Id_ProductPackageCategory) Add a new category?
</div>
<div class="editor-label">
Upgrade? :
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Upgrade)
#Html.ValidationMessageFor(model => model.Upgrade)
</div>
<br />
<div class="form-actions">
<button type="submit" class="btn btn-primary">Create</button>
</div>
</fieldset>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css")
}
In my view Index, I have this :
<div class="form-actions"><button type="button" id="create" class="btn btn-primary">Create</button> </div>
<div id ="create_person"></div>
And the way I load my Partial View :
$("#create").click(function () {
var form = $("#create_person").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
$.ajax({
url: "/Person/CreateOrUpdate",
type: "POST",
data: $("#create_person").serialize(),
cache: false
});
// var url = '/Person/CreatePerson';
// $("#create_person").load(url);
});
The actions :
[HttpGet]
public ActionResult CreateOrUpdate()
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name");
return View();
}
[HttpPost]
public JsonResult CreateOrUpdate(Person person)
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
db.Persons.AddObject(person);
db.SaveChanges();
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
If you post the page it will not come back to the dynamically loaded partial view. Try to make a ajax call to /Person/CreatePerson. Your CreatePerson will look similar to
[HttpPost]
public JsonResult CreatePerson(Person person)
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
try
{
if (!ModelState.IsValid)
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
throw new Exception("Please correct the following errors: " + Environment.NewLine + messages);
}
db.Persons.AddObject(person);
db.SaveChanges();
return Json(new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
} `
The ajax call to /Person/CreatePerson will look similar to
`
$.ajax({
url: '/Person/CreatePerson',
type: "POST",
data: $("#form").serialize(),
success: function (responce) {
alert(responce.Message);
},
error: function (xhr, textStatus) {
alert(xhr.status + " " + xhr.statusText);
}
});
Besides unobtrusive validation will not work easily with dynamic content. check the link unobtrusive validation on dynamically added partial view (not working)
I've developed a decent workaround for this. The partial page won't show the server errors on postback. First of all, we get the errors, send them back to the page, then create them in javascript & revalidate the page. Hopefully, hey presto!
In your controller:
if (ModelState.IsValid)
{
//... whatever code you need in here
}
var list = ModelStateHelper.AllErrors(ModelState);
TempData["shepherdErrors"] = list;
I put it in TempData so it can be retrieve easily from the partial. Yes, I called it shepherdErrors, it's my idea so I can call the concept whatever silly name I want! Shepherd the error codes to where they should be or something being the general idea.
In a helper class:
public class ModelStateHelper
{
public static IEnumerable<KeyValuePair<string, string>>
AllErrors(ModelStateDictionary modelState)
{
var result = new List<KeyValuePair<string, string>>();
var erroneousFields = modelState.Where(ms => ms.Value.Errors.Any())
.Select(x => new { x.Key, x.Value.Errors });
foreach (var erroneousField in erroneousFields)
{
var fieldKey = erroneousField.Key;
var fieldErrors = erroneousField.Errors
.Select(error => new KeyValuePair<string, string>(fieldKey, error.ErrorMessage)); //Error(fieldKey, error.ErrorMessage));
result.AddRange(fieldErrors);
}
return result;
}
}
Then on the html page somewhere after jquery being loaded:
function displayShepherdErrors() {
var shepherdErrors = JSON.parse('#(Newtonsoft.Json.JsonConvert.SerializeObject(TempData["shepherdErrors"]))'.replace(/"/g, '"'));
var frm;
var isShepherdErrors = (shepherdErrors && shepherdErrors.length > 0);
if (isShepherdErrors) {
errObj = {};
for (var i = 0; i < shepherdErrors.length; i++) {
var errorKey = shepherdErrors[i].Key; //also the id of the field
var errorMsg = shepherdErrors[i].Value;
var reg = new RegExp('^' + errorKey + '$', 'gi');
//find the selector - we use filter so we can find it case insensitive
var control = $('input').filter(function () {
if ($(this).attr('id'))
return $(this).attr('id').match(reg);
});
if (control && control.length) {
control = control[0];
var controlId = $(control).attr('name');
errObj[controlId] = errorMsg;
//get the containing form of the first input element
if (!frm)
frm = control.form;
}
}
var validator = $(frm).validate();
validator.showErrors(errObj);
}
return isShepherdErrors;
}
var isShepherdErrors = displayShepherdErrors();
This should work out of the box with general MVC development provided text boxes that are generated are based on the variable names - this is default behaviour of MVC.

Html.TextBoxFor showing Empty Value but the model is not empty

Hi all I'm having trouble correctly display the data in the textbox
This is my Print partialView
#{ Layout = null; }
#model Estudio.WebUI.Models.PrintViewModel
#using (Ajax.BeginForm("Print", new { #class = "openDialog data-dialog-id='PrintDialog' data-dialog-Title='Print'" }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "PrintDialog" }))
{
#Html.HiddenFor(m => m.FacturaId)
<div class="editor-label">
#Html.LabelFor(m => m.NComprobante)
<div class="editor-field">
#Html.TextBoxFor(m => m.NComprobante)
</div>
</div>
<br/>
<div class="editor-label">
#Html.LabelFor(m => m.SendMail)
<div class="editor-field">
#Html.CheckBoxFor(m => m.SendMail)
</div>
</div>
<input type="submit" name="Imprimir" value="Imprimir" id="Imprimir"/>
<script type="text/javascript">
$(document).ready(function () {
$("#NComprobante").mask("99999-999999999999");
});
</script>
}
This is ActionResult Print
public ActionResult Print(string id)
{
...
var model = new PrintViewModel
{
FacturaId = factura.FacturaId,
NComprobante = numero[0] + "-" + comprabante.ToString("000000000000")
};
return PartialView("Print", model);
}
Can anyone help?
wrong code on
NComprobante = numero[0] + "-" + comprabante.ToString("000000000000")
the correct is:
var comprabante = numero[0] + "-" + (Convert.ToDouble(numero[1]) + 1).ToString("0000000000000");

Getting information from my controller into onclick confirm(alert)

i try to confirm a sale and i need sum information about the product..
my View
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardModel.SerialNumber, "Serial No")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardModel.SerialNumber, new { id = "sn" })
#Html.ValidationMessageFor(model => model.CardModel.SerialNumber)
</div>
<p>
<input type="submit" value="CardSale" id="btnSubmit"
onclick="if (confirm('The owner dealer price is : **#Model.OwnerPrice** . Are you sure?')) { return true; } else { return false; }" />
</p>
</fieldset>
}
i tryed with the ' $.getJSON ' like this:
<script type="text/javascript">
$(document).ready(function()
{
$("#btnSubmit").click(function ()
{
var serial = $("#sn");
var price = "";
var url = "";
url = "#Url.Action("GetOwnerPrice","Card")/"+serial;
$.getJSON(url,function(data)
{
alert(data.Value);
});
});
});
and on the controller
public ActionResult GetOwnerPrice(int sn)
{
var owner = db.Dealers.Single(s => s.DealerID == db.Dealers.Single(o => o.UserName == User.Identity.Name).OwnerDealerID);
var ownerPrice = owner.ProductToSale.Single(pr => pr.ProductID == sn).SalePrice;
return Json(ownerPrice, JsonRequestBehavior.AllowGet);
}
but i dont know how to return it to the onclick confirm msg or into my ViewModel..
any help?
The way in which you have written it, the #Model.OwnerPrice value must be known during page generation, since the template engine only has values that exist in your model when it does the template-data merge.
If you do know this value during page load, then simply use the value in your model exactly as you have, and if the user ever gets to this dialog, they will see the proper value.
If the value of this confirmation dialog is not known during page load, then you have the right idea to retrieve it via an Ajax call. The trick is to update the DOM with the new information when the call finishes. You can do this in three steps. First, change your dialog box:
First:
if (confirm('The owner dealer price is : ' + ownerDealerPrice + '. Are you sure?'))
Second:
Declare a new global variable:
var ownerDealerPrice;
Third:
Get the price:
$.ajax({ url: "/GetOwnerPrice", type: "GET", data: "serial=" + serial })
.success(function (price) {ownerDealerPrice = price; }
});
finnaly i take the two answare =)
my view:
#model oCc.IPToGo.ViewModel.CardSaleViewModel
#{
ViewBag.Title = "Card Sale";
var ownerDealerPrice = 0;
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardModel.SerialNumber, "Serial No")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardModel.SerialNumber)
#Html.ValidationMessageFor(model => model.CardModel.SerialNumber)
</div>
<p>
<input type="submit" value="CardSale" />
</p>
</fieldset>
}
<script type="text/javascript">
$(document).submit(function()
{
var serial = "";
serial = $("#CardModel_SerialNumber").val();
var uurl = "";
uurl = "#Url.Action("GetOwnerPrice","Card")/"+serial;
$.ajaxSetup({ cache: false });
$.ajax({ async: false , url: uurl, dataype : 'json', method : 'GET'})
.success(function (price) {ownerDealerPrice = price;
$.ajaxSetup({ cache: true });
});
return (confirm('The owner dealer price is : ' + ownerDealerPrice + '. Are you sure?'))
});
the controller code
public ActionResult GetOwnerPrice(string ID)
{
var currentDealer = db.Dealers.Single(o => o.UserName == User.Identity.Name);
var owner = db.Dealers.Single(s => s.DealerID ==currentDealer.OwnerDealerID);
var card = db.Cards.Single(s => s.SerialNumber == ID);
var ownerPrice = owner.ProductToSale.Single(pr => pr.ProductID == card.ProductID).SalePrice;
return Json(ownerPrice, JsonRequestBehavior.AllowGet);
}
Did you try $.ajax with async = false?
It will return control right into your click handler. Something like:
var tmp = 0;
$.ajax({
async = false,
url = ...,
dataype = 'json',
method = 'POST'})
.complete(function(data) {
tmp = data
});
if(confirm("my message here: " + tmp)) {... }

Categories