ASP.NET MVC - Reusing Partial Views? - asp.net-mvc
I am trying to reuse "Competencia" as a partial view in another page. Just like the old web controls.
When I run as a "normal page", saying, typing
http://mydomain/Competencia
the control works fine. When I use is as a partial view, it does not render
#section Scripts {
<script src="#Url.Content("~/ViewScripts/Competencia/Index.js")" type="text/javascript"></script>
}
and obviously, can't find the method PopularGridArquivo inside it.
Here are the codes:
Competencia/Index.js
/// <reference path="Competencia.js" />
function PopularGridArquivo(mes) {
if (mes != "") {
$.ajax({
url: '/Competencia/ListarArquivosCompetencia',
type: 'post',
data: {
competencia: mes,
caminhoArquivo: $("#path").val()
},
success: function (html) {
$("#divDetalhe").html(html);
},
error: function (a, b, c) {
alert(c);
}
});
}
else {
$("#divdetalhe").html('');
}
}
CompetenciaController:
public class CompetenciaController : Controller
{
//
// GET: /Competencia/
public ActionResult Index()
{
Competencia compet = new Competencia();
compet.pathCompetencias = #"c:\temp\MUMPS\";
ViewBag.Competencia = compet;
return View(compet);
}
[HttpPost]
//public PartialViewResult ListarArquivosCompetencia(string competencia, string caminhoArquivo)
public PartialViewResult ListarArquivosCompetencia(string competencia, string caminhoArquivo)
{
IList<FileInfo> listaArquivos = null;
IList<CargaArquivos> listaCargaArquivos = new List<CargaArquivos>();
CargaArquivos oCargaArquivos = null;
//Popular combo de meses
//caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
//string caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
//DateTime data = new DateTime(DateTime.Now.Year, mes, 1);
caminhoArquivo = string.Format("{0}{1:MMyyyy}", caminhoArquivo, competencia);
listaArquivos = PastaArquivo.ListarArquivosDiretorio(caminhoArquivo);
if (listaArquivos.Count > 0)
{
foreach (var item in listaArquivos)
{
oCargaArquivos = new CargaArquivos();
oCargaArquivos.CaminhoArquivo = item.DirectoryName;
oCargaArquivos.NomeArquivo = item.Name;
listaCargaArquivos.Add(oCargaArquivos);
}
ViewBag.listaCargaArquivos = listaCargaArquivos;
}
//return PartialView("_DetalheCarga", ViewBag.listaCargaArquivos);
return PartialView("_DetalheCarga", ViewBag.listaCargaArquivos);
}
}
/Views/Competencia/Index.cshtml
#model IcatuValor.Models.Competencia
#section Scripts {
<script src="#Url.Content("~/ViewScripts/Competencia/Index.js")" type="text/javascript"></script>
}
<fieldset>
<div class="left-column">
#Html.Hidden("path", Model.pathCompetencias)
<label class="control-label"> Competência: #Html.DropDownList("ddMeses", new SelectList(Model.Competencias, "Key", "Value"), "Selecione", new { onChange = "JavaScript: PopularGridArquivo(this.value);", #class = "dropdown" })</label>
</div>
<div id="divDetalhe"></div>
#{
if (Model.arquivos != null)
{
Html.RenderPartial("_DetalheCarga", (IList<ViewModels.CargaArquivos>)ViewBag.listaCargaArquivos);
//Html.Partial("_DetalheCarga");
}
}
</fieldset>
Model Competencia:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace IcatuValor.Models
{
public class Competencia
{
public string pathCompetencias { get; set; }
public string pathSubDir { get; set; }
public IEnumerable<KeyValuePair<string, string>> Competencias
{
get
{
//Expressão regular para validar o nome da pasta como formato MMYYYY
var re = new Regex(#"^(0[1-9]|1[0-2])(19|2[0-1])\d{2}$");
DirectoryInfo dirInfo = new DirectoryInfo(pathCompetencias);
foreach (DirectoryInfo dir in dirInfo.GetDirectories())
{
//Somente entram na listagem diretórios que satisfizerem o formato MMYYYY
if (re.IsMatch(dir.Name))
yield return new KeyValuePair<string, string>
(
dir.Name,
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Convert.ToInt16(dir.Name.Substring(0, 2))) + "/" + dir.Name.Substring(2)
);
}
}
}
public IList<DirectoryInfo> Subdiretorios
{
get
{
DirectoryInfo di = new DirectoryInfo(pathSubDir);
return di.GetDirectories();
}
}
public IList<FileInfo> arquivos
{
get;
set;
}
}
}
And finally, the another page, which will use "Competencia" inside it:
Cargamumps/Index.cshtml
#section Scripts {
<script src="#Url.Content("~/ViewScripts/CargaMumps/Index.js")" type="text/javascript"></script>
}
<fieldset>
<legend>Carregar Arquivos</legend>
#*<div class="input-append date datepicker" data-date-format="dd/mm/yyyy">
<label class="lbl">Data início</label>
<input type="text" class="datePicker" name="DataInicio" id="DataInicio" style="width: auto">
</div>*#
<div class="input-append" id="divArquivos">
<div class="input-append">
<label class="control-label">LF02 (LF02AAAAMM.TXT):</label>
#Html.TextBox("filLF02", null, new { type = "file", #class = "input-large" })
</div>
<div class="input-append">
<label class="control-label">LF03 (LF03AAAAMM.TXT):</label>
#Html.TextBox("filLF03", null, new { type = "file", #class = "input-large" })
</div>
<div class="input-append">
<label class="control-label">Pendência Atual (PendentesAAAAMM.txt):</label>
#Html.TextBox("filPendentes", null, new { type = "file", #class = "input-large" })
</div>
<div class="input-append">
<label class="control-label">Pendência Anterior (PendentesAAAAMM.txt):</label>
#Html.TextBox("filPendentesAnterior", null, new { type = "file", #class = "input-large" })
</div>
<br />
<div class="input-append">
<button type="submit" class="btn btn-primary" id="btnSubmit">Executar Matemática</button>
</div>
</div>
</fieldset>
<fieldset>
#{
//RENDERS OK
Html.RenderPartial("~/Views/Competencia/Index.cshtml", (IcatuValor.Models.Competencia)ViewBag.Competencia);
}
</fieldset>
CargamumpsController.cs
using System.Web.Mvc;
using System;
using DAL.Repository;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using ViewModels;
using DAL;
using System.Text.RegularExpressions;
using System.Management;
using System.Text;
using System.Runtime.InteropServices;
using System.Net;
using System.Collections;
using System.Diagnostics;
using IcatuValor.Utils;
using IcatuValor.Models;
namespace IcatuValor.Controllers
{
public class CargaMumpsController : Controller
{
#region Actions
private Dictionary<string, string> dictionary = new Dictionary<string, string>();
public enum ELivro
{
LF02 = 1,
LF03 = 2,
Pendentes = 3,
PendentesAnterior = 4
}
public ActionResult Index()
{
//Pega o mês anterior ultimo fechamento
DateTime now = DateTime.Now.AddMonths(-1);
Competencia compet = new Competencia();
compet.pathCompetencias = #"c:\temp\MUMPS\";
ViewBag.Competencia = compet;
return View();
//ListarArquivosMes(now.Month);
//return View();
}
[HttpPost]
public string Upload(FormCollection form)
{
try
{
ProcedureRepository procedureRepository = new ProcedureRepository();
DataTable dtResultado = null;
double somaEmissoes, somaCancelamentos, somaPagos, somaPendente, somaPendenteAnterior;
Stopwatch st = new Stopwatch();
st.Start();
string pathLF02 = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo1"]);
string pathLF03 = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo2"]);
string pathPendentes = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo3"]);
string pathPendentesAnterior = Utils.PastaArquivo.RetornarcaminhoArquivo(form["arquivo4"]);
//Pegar mes atual e anterior com base no mes e ano dos nomes dos arquivos.
FileInfo fi = new FileInfo(pathLF02);
int ano, mes;
if (!int.TryParse(fi.Name.Substring(4, 4), out ano) || !int.TryParse(fi.Name.Substring(8, 2), out mes))
throw new Exception("O nome do arquivo LF02 deve estar no formato 'LF02AAAAMM.TXT'.\n\nAAAA - Ano com 4 digitos\nMM - Mês com 2 dígitos.");
DateTime dataFechamento = new DateTime(ano, mes, 1);
//DateTime dataFechamento = Convert.ToDateTime(form["dtInicio"]);
IDataReader dr;
#region LF02
if (!string.IsNullOrEmpty(pathLF02))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathLF02);
//AjustarColunas(dtResultado, ELivro.LF02);
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathLF02);
procedureRepository.TruncarTabela("dbo.LivroMumps_LF02");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_LF02");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_LF02");
//dtResultado.Clear();
}
#endregion
#region LF03
if (!string.IsNullOrEmpty(pathLF03))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathLF03);
//AjustarColunas(dtResultado, ELivro.LF03);
//procedureRepository.TruncarTabela("dbo.LivroMumps_LF03");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_LF03");
//dtResultado.Clear();
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathLF03);
procedureRepository.TruncarTabela("dbo.LivroMumps_LF03");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_LF03");
}
#endregion
#region Pendentes
if (!string.IsNullOrEmpty(pathPendentes))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathPendentes);
//AjustarColunas(dtResultado, ELivro.Pendentes);
//procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_Pendentes");
//dtResultado.Clear();
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathPendentes);
procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_Pendentes");
}
#endregion
#region Pendentes Mês Anterior
if (!string.IsNullOrEmpty(pathPendentesAnterior))
{
//dtResultado = Utils.PastaArquivo.CriarDataTable(pathPendentesAnterior);
//AjustarColunas(dtResultado, ELivro.PendentesAnterior);
//procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes_Anterior");
//procedureRepository.ExecutarBulkInsert(dtResultado, "dbo.LivroMumps_Pendentes_Anterior");
//dtResultado.Clear();
dr = Utils.PastaArquivo.CriarOleDbDataReader(pathPendentesAnterior);
procedureRepository.TruncarTabela("dbo.LivroMumps_Pendentes_Anterior");
procedureRepository.ExecutarBulkInsert(dr, "dbo.LivroMumps_Pendentes_Anterior");
}
#endregion
dtResultado = procedureRepository.CalcularFechamentoMumps(dataFechamento, out somaEmissoes, out somaCancelamentos, out somaPagos, out somaPendente, out somaPendenteAnterior);
GerarPlanilhaExcel(dtResultado, dataFechamento, somaEmissoes, somaCancelamentos, somaPagos, somaPendente, somaPendenteAnterior);
//TODO - VERIFICAR NECESSIDADE DE ENVIAR E-MAIL.
//EnviarEmail(dataFechamento);
st.Stop();
return "Calculo executado com sucesso.\n\nTempo de execução: " + st.Elapsed.ToString();
}
catch (Exception ex)
{
PastaArquivo.EscreveLog(ex.ToString());
return ex.ToString();
}
}
private void EnviarEmail(DateTime dtCompetencia)
{
string emailPara = System.Configuration.ConfigurationManager.AppSettings["EmailPara"].ToString();
string mesAnoCompetencia = dtCompetencia.ToString("MM/yyyy");
string msgEmail = "Fechamento de prêmios (MUMPS) referente a " + mesAnoCompetencia + " concluído com sucesso!";
string assuntoEmail = "Fechamento " + mesAnoCompetencia + " - MUMPS";
string emailDe = System.Configuration.ConfigurationManager.AppSettings["EmailDe"].ToString();
if (!string.IsNullOrEmpty(emailPara) && !string.IsNullOrEmpty(emailDe))
Utils.Email.EnviarEmail(emailDe, emailPara, msgEmail + "\n \n", assuntoEmail);
}
private void GerarPlanilhaExcel(DataTable dtResultado, DateTime dataFechamento, double somaEmissoes, double somaCancelamentos, double somaPagos, double somaPendente, double somaPendenteAnterior)
{
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//Pega o caminho onde será salvo o nosso arquivo
string caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
//Criar uma pasta para identificar o mes referencia
caminhoArquivo = string.Format("{0}{1:MMyyyy}", caminhoArquivo, dataFechamento);
Utils.PastaArquivo.VerificaExistenciaECriaPasta(caminhoArquivo);
string filename = string.Format(#"{0}\Pend_{1:MMyyyy}.xls", caminhoArquivo, dataFechamento);
// Verifica se existe algum arquivo com o mesmo nome e caminho de destino, se existir exclui
if (System.IO.File.Exists(filename)) System.IO.File.Delete(filename);
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(Server.MapPath("~/LivrosMumps/Template.xls"), 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, false, false, false);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.get_Range("A2").Value = string.Format("CONTROLE DE RELATÓRIOS - {0:MM/yyyy}", dataFechamento);
xlWorkSheet.get_Range("B6;B35;B67;B97;B128").Value = string.Format("{0:MM/yyyy}", dataFechamento.AddMonths(-1));
xlWorkSheet.get_Range("F6;F35;F67;F97;F128").Value = string.Format("{0:MM/yyyy}", dataFechamento);
InserirValores(dtResultado, xlWorkSheet);
xlWorkBook.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(false, filename, misValue);
xlApp.Quit();
Utils.PastaArquivo.liberarObjetos(xlWorkSheet);
Utils.PastaArquivo.liberarObjetos(xlWorkBook);
Utils.PastaArquivo.liberarObjetos(xlApp);
}
/// <summary>
/// Insere os valores na planilha template
/// </summary>
/// <param name="dtResultado">Datatable com os valores do livro</param>
/// <param name="xlWorkSheet">Planilha</param>
private void InserirValores(DataTable dtResultado, Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet)
{
List<string> result;
ProcedureRepository pr = new ProcedureRepository();
foreach (DataRow dr in dtResultado.Rows)
{
result = pr.ObterValoresLivroMumps(Convert.ToInt16(dr["COD_RAMO"].ToString()), dr["SUCURSAL"].ToString());
if (result.Count > 0)
{
xlWorkSheet.get_Range(result[0]).Value = Convert.ToDouble(dr["PREMIO_PENDENTE_ANT"].ToString());
xlWorkSheet.get_Range(result[1]).Value = Convert.ToDouble(dr["PREMIO_EMITIDO"].ToString());
xlWorkSheet.get_Range(result[2]).Value = Convert.ToDouble(dr["PREMIO_CANCELADO"].ToString());
xlWorkSheet.get_Range(result[3]).Value = Convert.ToDouble(dr["PREMIO_PAGO"].ToString());
xlWorkSheet.get_Range(result[4]).Value = Convert.ToDouble(dr["PREMIO_PENDENTE"].ToString());
}
}
}
[HttpPost]
public ActionResult AbrirArquivoExcel(CargaArquivos cargaArquivos)
{
Utils.PastaArquivo.ExportarCSV(cargaArquivos.CaminhoArquivo + #"\" + cargaArquivos.NomeArquivo);
return View();
}
[HttpPost]
//public PartialViewResult ListarArquivosMes(int mes)
//{
// IList<FileInfo> listaArquivos = null;
// IList<CargaArquivos> listaCargaArquivos = new List<CargaArquivos>();
// CargaArquivos oCargaArquivos = null;
// //Popular combo de meses
// ViewBag.ListaMeses = Model.AllMonths;
// string caminhoArquivo = System.Configuration.ConfigurationManager.AppSettings["FullPathExcelCalculoFechamentoMumps"].ToString();
// DateTime data = new DateTime(DateTime.Now.Year, mes, 1);
// caminhoArquivo = string.Format("{0}{1:MMyyyy}", caminhoArquivo, data);
// listaArquivos = Utils.PastaArquivo.ListarArquivosDiretorio(caminhoArquivo);
// if (listaArquivos.Count > 0)
// {
// foreach (var item in listaArquivos)
// {
// oCargaArquivos = new CargaArquivos();
// oCargaArquivos.CaminhoArquivo = item.DirectoryName;
// oCargaArquivos.NomeArquivo = item.Name;
// listaCargaArquivos.Add(oCargaArquivos);
// }
// ViewBag.listaCargaArquivos = listaCargaArquivos;
// }
// return PartialView("_DetalheCarga", ViewBag.listaCargaArquivos);
//}
#endregion
#region Métodos privados
/// <summary>
/// Faz o de-para das colunas do TXT para as colunas da Base de Dados
/// </summary>
/// <param name="dtResultado"></param>
/// <param name="livro"></param>
private void AjustarColunas(DataTable dtResultado, ELivro livro)
{
dictionary.Clear();
switch (livro)
{
case ELivro.LF02:
LerDictionaryLF02();
break;
case ELivro.LF03:
LerDictionaryLF03();
break;
case ELivro.Pendentes:
case ELivro.PendentesAnterior:
LerDictionaryPendentes();
break;
}
foreach (DataColumn dc in dtResultado.Columns)
{
if (dictionary.FirstOrDefault(x => x.Key == dc.ColumnName).Value == null)
throw new Exception(string.Format("Coluna: {0} inválida no livro {1}.", dc.ColumnName, livro.ToString()));
dc.ColumnName = dictionary[dc.ColumnName];
}
}
private void LerDictionaryLF02()
{
dictionary.Add("sucursal", "Sucursal");
dictionary.Add("ramo", "Ramo");
dictionary.Add("data emissao", "DataEmissao");
dictionary.Add("numero da cobranca", "Numero_da_Cobranca");
dictionary.Add("numero da apolice", "Numero_da_Apolice");
dictionary.Add("segurado ou estipulante", "Segurado_ou_Estipulante");
dictionary.Add("inicio seguro", "Inicio_Seguro");
dictionary.Add("termino seguro", "Termino_Seguro");
dictionary.Add("parcela/fatura", "Parcela_Fatura");
dictionary.Add("premio da lider", "Premio_da_Lider");
dictionary.Add("premio das cosseguradoras", "Premio_das_Cosseguradoras");
dictionary.Add("custo de emissao", "Custo_de_Emissao");
dictionary.Add("iof", "IOF");
dictionary.Add("premio total", "Premio_Total");
dictionary.Add("risco", "Risco");
dictionary.Add("produto", "Produto");
dictionary.Add("data venc fat", "Data_Venc_Fat");
dictionary.Add("data pagto fat", "Data_Pagto_Fat");
dictionary.Add("data emissao_", "Data_Emissao_Cancelamento");
dictionary.Add("quantidade de vidas", "Quantidade_de_Vidas");
dictionary.Add("descricao da periodicidade de pagamento", "Descr_Period_Pagamento");
dictionary.Add("tipo de apolice", "Tipo_de_Apolice");
dictionary.Add("competencia inicial", "Competencia_Inicial");
dictionary.Add("competencia final", "Competencia_Final");
dictionary.Add("data da arrecadacao", "Data_da_Arrecadacao");
dictionary.Add("ipd", "IPD");
dictionary.Add("idade", "Idade");
dictionary.Add("data de nascimento", "Data_de_Nascimento");
dictionary.Add("codigo da periodicidade de pagamento", "Codigo_Period_Pagamento");
dictionary.Add("matricula", "Matricula");
dictionary.Add("taxa", "Taxa");
dictionary.Add("importancia segurada", "Importancia_Segurada");
dictionary.Add("canal", "Canal");
dictionary.Add("ccusto", "CCusto");
dictionary.Add("unidprod", "UnidProd");
dictionary.Add("corretagem", "Corretagem");
dictionary.Add("angariacao", "Angariacao");
dictionary.Add("pro-labore", "Pro_labore");
dictionary.Add("keyaccount", "KeyAccount");
}
private void LerDictionaryLF03()
{
dictionary.Add("sucursal", "Sucursal");
dictionary.Add("ramo", "Ramo");
dictionary.Add("data de emissão", "Data_Emissao");
dictionary.Add("data de emiss?", "Data_Emissao");
dictionary.Add("ordem da apolice", "Ordem_Apolice");
dictionary.Add("numero da apolice", "Numero_Apolice");
dictionary.Add("parcela", "Parcela");
dictionary.Add("segurado/estipulante", "Segurado_Estipulante");
dictionary.Add("produto", "Produto");
dictionary.Add("ini seguro", "InicioSeguro");
dictionary.Add("prem/juros", "Prem_Juros");
dictionary.Add("premio da lider", "PremioLider");
dictionary.Add("custo de emissao", "Custo_Emissao");
dictionary.Add("iof", "IOF");
dictionary.Add("premio total", "PremioTotal");
dictionary.Add("fatura", "Fatura");
dictionary.Add("a/r", "AR");
dictionary.Add("risco", "Risco");
dictionary.Add("dt ef cob", "Dt_Ef_Cob");
dictionary.Add("cpf/cnpj", "CPF_CNPJ");
dictionary.Add("fim seguro", "Fim_Seguro");
dictionary.Add("juros da lider", "Juros_Lider");
dictionary.Add("juros cossegur.", "Juros_Cosseguro");
dictionary.Add("corretagem", "Corretagem");
dictionary.Add("angariacao", "Angariacao");
dictionary.Add("pro-labore", "ProLabore");
dictionary.Add("comp inicial", "CompInicial");
}
private void LerDictionaryPendentes()
{
dictionary.Add("unidade produtora", "Unidade_Produtora");
dictionary.Add("ramo", "Ramo");
dictionary.Add("produto", "Produto");
dictionary.Add("data emissao", "Data_Emissao");
dictionary.Add("cobranca", "Cobranca");
dictionary.Add("apolice", "Apolice");
dictionary.Add("estipulante", "Estipulante");
dictionary.Add("vigencia", "Vigencia");
dictionary.Add("data vencimento", "Data_Vencimento");
dictionary.Add("valor bruto emitido", "Valor_Bruto_Emitido");
dictionary.Add("fatura", "Fatura");
dictionary.Add("cod ramo_produto", "Cod_Ramo_Produto");
dictionary.Add("descricao", "Descricao");
dictionary.Add("cod canal", "Cod_Canal");
dictionary.Add("descricao_", "Descricao_Canal");
dictionary.Add("sucursal", "Sucursal");
dictionary.Add("centro de custo", "CCusto");
dictionary.Add("corretagem", "Corretagem");
dictionary.Add("angariacao", "Angariacao");
dictionary.Add("prolabore", "Prolabore");
dictionary.Add("keyaccount", "KeyAccount");
dictionary.Add("vl_iof", "Vl_IOF");
}
#endregion
}
}
If I'm understanding you correctly, you have a strongly-typed view that you would like to use on multiple pages (Cargamumps/Index and Competencia/Index.cshtml). These two Index pages both share the same ViewModel type Competencia.
If this is the case, I would suggest extracting the common content into a partial view under Shared/EditorTemplates or Shared/DisplayTemplates. Then in the two index views, do a call to EditorFor or DisplayFor.
Html.EditorFor(m => m);
or
Html.DisplayFor(m => m);
If your ViewData.Model is type Competencia, this will locate the proper editor/display template and render it inline, as well as properly construct the id/name of any controls so that model binding works out of the box.
Related
Polymorphic model binding / Complex Models
I have problem in model binding. When I submit form it returns me id=0 and device is null? and how to solve it. My goal is to add new device, and choose device type from view by selector. if user selects smartphone it has to add fields for smartphone. I don't want to save device type in base class as Kind variable. Thanks in advance(sorry for english) controller-> public IActionResult Index() { MainCont mainCont = new MainCont(); return View(mainCont); } index.cshtml -> #model MainCont #{ ViewData["Title"] = "Home Page"; } <form action="home/create" method="post"> #Html.Partial("example",Model.Device) <button type="submit">გაგზავნა</button> </form> example.cshtml -> #model SmartPhone #Html.TextBoxFor(model => model.imei) #Html.TextBoxFor(model => model.screensize) Device Model -> public abstract class Device : Object { } LaptopModel -> public class Laptop : Device { public string CPU { get; set; } public string GPu { get; set; } } MainCont -> public class MainCont { public int Id{ get; set; } public Device Device { get; set; } } SmartphoneModel -> public class SmartPhone : Device { public string screensize { get; set; } public string imei { get; set; } } model binder -> using Bind.Models; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bind { public class DeviceModelBinder : IModelBinder { private Dictionary<Type, (ModelMetadata, IModelBinder)> binders; public DeviceModelBinder(Dictionary<Type, (ModelMetadata, IModelBinder)> binders) { this.binders = binders; } public async Task BindModelAsync(ModelBindingContext bindingContext) { IModelBinder modelBinder; ModelMetadata modelMetadata; if (bindingContext.ModelType == typeof(Laptop)) { (modelMetadata, modelBinder) = binders[typeof(Laptop)]; } else if (bindingContext.ModelType == typeof(SmartPhone)) { (modelMetadata, modelBinder) = binders[typeof(SmartPhone)]; } else { bindingContext.Result = ModelBindingResult.Failed(); return; } var newBindingContext = DefaultModelBindingContext.CreateBindingContext( bindingContext.ActionContext, bindingContext.ValueProvider, modelMetadata, bindingInfo: null, bindingContext.ModelName); await modelBinder.BindModelAsync(newBindingContext); bindingContext.Result = newBindingContext.Result; if (newBindingContext.Result.IsModelSet) { // Setting the ValidationState ensures properties on derived types are correctly bindingContext.ValidationState[newBindingContext.Result] = new ValidationStateEntry { Metadata = modelMetadata, }; } } } } binderprovider -> using Bind.Models; using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bind { public class DeviceModelBinderProvider: IModelBinderProvider { public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context.Metadata.ModelType != typeof(Device)) { return null; } var subclasses = new[] { typeof(Laptop), typeof(SmartPhone), }; var binders = new Dictionary<Type, (ModelMetadata, IModelBinder)>(); foreach (var type in subclasses) { var modelMetadata = context.MetadataProvider.GetMetadataForType(type); binders[type] = (modelMetadata, context.CreateBinder(modelMetadata)); } return new DeviceModelBinder(binders); } } }
Here is a demo: Index.cshtml(when select SmartPhone,use example.cshtml,when select Laptop,use example1.cshtml): #model MainCont #{ ViewData["Title"] = "Home Page"; } <form asp-action="create" asp-controller="home" method="post"> <select id="select" name="select"> <option value="SmartPhone">SmartPhone </option> <option value="Laptop">Laptop </option> </select> <div id="sample"></div> <button type="submit">გაგზავნა</button> </form> #section scripts{ <script> $(function () { GetPartialView(); }) $("#select").change(function () { GetPartialView(); }) function GetPartialView() { $.ajax({ url: "/Test1/ReturnExample", type: "POST", data: { select: $("#select").val() }, success: function (data) { $('#sample').html(data); }, error: function (reponse) { alert("error : " + reponse); } }); } </script> } example.cshtml: #model SmartPhone #Html.TextBoxFor(model => model.imei) #Html.TextBoxFor(model => model.screensize) example1.cshtml: #model Laptop #Html.TextBoxFor(model => model.CPU) #Html.TextBoxFor(model => model.GPu) Controller: public IActionResult Index() { return View(new MainCont()); } public IActionResult ReturnExample(string select) { if (select == "SmartPhone") { return PartialView("~/Views/Test1/example.cshtml", new SmartPhone()); } else { return PartialView("~/Views/Test1/example1.cshtml", new Laptop()); } } Create Action in Home Controller: [HttpPost] public IActionResult Create([ModelBinder(typeof(DataBinder))]MainCont mainCont) { return Ok(); } DataBinder: public class DataBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var model1 = new MainCont(); var select = bindingContext.ValueProvider.GetValue("select").FirstValue; if (select == "SmartPhone") { var model2 = new SmartPhone(); model2.screensize = bindingContext.ValueProvider.GetValue("screensize").FirstValue; model2.imei = bindingContext.ValueProvider.GetValue("imei").FirstValue; model1.Device = model2; } else if (select == "Laptop") { var model2 = new Laptop(); model2.CPU = bindingContext.ValueProvider.GetValue("CPU").FirstValue; model2.GPu = bindingContext.ValueProvider.GetValue("GPu").FirstValue; model1.Device = model2; } bindingContext.Result = ModelBindingResult.Success(model1); return Task.CompletedTask; } } result:
How to fill dropdownlist in MVC-4 using dapper
I filled Drop Down List in MVC which is working fine but now I want to do it using Dapper but got stuck. DropDownList in MVC without Dapper Controller [HttpPost] public ActionResult Create(User ur) { string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True"; SqlConnection con = new SqlConnection(str); string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')"; con.Open(); SqlCommand cmd = new SqlCommand(query, con); cmd.ExecuteNonQuery(); con.Close(); TempData["msg"] = "<script>alert('Inserted Successfully');</script>"; ModelState.Clear(); FillCountry(); } public void FillCountry() { string str = #"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True"; SqlConnection con = new SqlConnection(str); string query = "select * from tbl_country "; SqlCommand cmd = new SqlCommand(query, con); con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); List<SelectListItem> li = new List<SelectListItem>(); li.Add(new SelectListItem { Text = "Select", Value = "0" }); while (rdr.Read()) { li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() }); } ViewData["country"] = li; } View #{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); } #Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new {onchange = "this.form.submit();" }) #{ Html.EndForm(); } This is what I am trying to do now DropDownList in MVC with Dapper Model public class Region { private int _CountryId; private string _CountryName; public int CountryId { get { return _CountryId; } set { _CountryId = value; } } public string CountryName { get { return _CountryName; } set { _CountryName = value; } } Controller [HttpPost] public ActionResult AddMobiles(TBMobileDetails MD, HttpPostedFileBase file) { FileUpload(file); MobileMain MM = new MobileMain(); MM.AddMobiles(MD); FillCountry(); return RedirectToAction("AllMobileList"); } Stuck in this part how to fill it using dapper? How to populate my list? public void FillCountry() { List<Region> li = new List<Region>(); var para = new DynamicParameters(); para.Add("#Type", 1); var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure); } View #{ Html.BeginForm("AddMobiles", "AddMobile", FormMethod.Post, new { enctype = "multipart/form-data" }); } #Html.DropDownList("country", ViewData["country"] as List<SelectListItem>, new { onchange = "this.form.submit();" }) #{ Html.EndForm(); }
You are passing in ViewData["country"] object of type IEnumerable<Region> while in View you are casting it to IEnumerable<SelectListItem> which won't work obviously in action change FillCountry() to make SelectList: public void FillCountry() { List<Region> li = new List<Region>(); var para = new DynamicParameters(); para.Add("#Type", 1); var result = con.Query<Region>("Sp_MVCDapperDDl", para, commandType: CommandType.StoredProcedure); var list = new SelectList(result,"CountryId","CountryName"); } and in View now cast it to SelectList: #Html.DropDownList("country", ViewData["country"] as SelectList, new {onchange = "this.form.submit();" }) This will get you going.
DevExpress GridView ExportToPdf doesn't export filtered data MVC
I have a webpage with gridview from Devexpress and i've implemented export to pdf. But somehow I don't get the current filter, order or group setting. I'm wondering if there is something wrong with how i set my setting in code or something since I've googled a lot at seems like those options should be handled automatically in ExportToPdf as long as you have rigth setting. My _GripPartial.cshtml: #Html.DevExpress().GridView(TreeMenuTest.Controllers.LogViewController.GridViewSettings).Bind(TreeMenuTest.Controllers.LogViewController.DataSource).GetHtml() _LogView.cshtml: #using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post)) { <div id="buttonExport" class ="gridBtn"> <input type="submit" id ="ExportBtn" value="Export to pdf" /> </div>} <div id="buttonReset" class ="gridBtn"> <input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/> </div> #Html.Action("Grid","LogView") And finally LogViewController: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.SqlClient; using TreeMenuTest.Models; using DevExpress.Web.Mvc; using DevExpress.Web.ASPxGridView; using System.Globalization; using System.Web.UI.WebControls; using DevExpress.Web.ASPxClasses; using DevExpress.XtraPrinting; using DevExpress.XtraPrintingLinks; using System.IO; using System.Drawing.Printing; namespace TreeMenuTest.Controllers { public class LogViewController : Controller { // // GET: /LogView/ public static List<LoggingEvent> DataSource; static GridViewSettings exportGridViewSettings; public static GridViewSettings GridViewSettings { get { if (exportGridViewSettings == null) exportGridViewSettings = GetGridViewSettings(); return exportGridViewSettings; } } static GridViewSettings GetGridViewSettings() { GridViewSettings settings = new GridViewSettings(); settings.Name = "GridView"; settings.CallbackRouteValues = new { Controller = "LogView", Action = "Grid" }; settings.Width = Unit.Percentage(100); settings.Theme = "BlackGlass"; settings.KeyFieldName = "Id"; settings.SettingsPager.Visible = true; settings.Settings.ShowGroupPanel = true; settings.Settings.ShowFilterRow = true; settings.SettingsBehavior.AllowSelectByRowClick = true; settings.SettingsPager.PageSize = 25; settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control; settings.Settings.ShowHeaderFilterButton = true; settings.SettingsPopup.HeaderFilter.Height = 200; settings.SettingsExport.Landscape = true; settings.SettingsExport.TopMargin = 0; settings.SettingsExport.LeftMargin = 0; settings.SettingsExport.RightMargin = 0; settings.SettingsExport.BottomMargin = 0; settings.SettingsExport.PaperKind = PaperKind.A4; settings.SettingsExport.RenderBrick = (sender, e) => { if (e.RowType == GridViewRowType.Data && e.VisibleIndex % 2 == 0) e.BrickStyle.BackColor = System.Drawing.Color.FromArgb(0xEE, 0xEE, 0xEE); }; settings.Columns.Add("Id"); settings.Columns.Add(column => { column.FieldName = "Ts"; column.Settings.AutoFilterCondition = AutoFilterCondition.Like; }); settings.Columns.Add("LogLevelText").Caption = "Level"; settings.Columns.Add("LoggerName"); settings.Columns.Add("Message"); settings.Columns.Add("ThreadName").Caption = "Thread"; settings.Columns.Add("UserName"); settings.Columns.Add("Domain"); settings.Columns.Add("ClassName"); settings.Columns.Add("FileName"); settings.Columns.Add("MethodName").Caption = "Method"; settings.Columns.Add("LineNumber").Caption = "Line"; settings.Columns.Add("LocalIP"); settings.Columns.Add("MachineName").Caption = "Machine"; settings.Columns.Add("UnikeName"); settings.Settings.ShowPreview = true; settings.PreviewFieldName = "ExceptionString"; return settings; } public ActionResult Index() { return PartialView("_LogView"); } public ActionResult Grid() { if (DataSource == null) { DataSource = GetAllEventsLast24h(); } return PartialView("_GridPartial"); } public ActionResult EmptyGrid() { DataSource = null; return PartialView("_GridPartial"); } public List<LoggingEvent> GetAllEventsLast24h() { return GetEventsWithCommand("where Ts > '" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss") + "';"); } public List<LoggingEvent> GetEventsOnDateTime(DateTime fromDate, DateTime toDate) { return GetEventsWithCommand("where Ts > '" + fromDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND Ts < '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "';"); } public List<LoggingEvent> GetEventsWithCommand(string where) { List<LoggingEvent> events = new List<LoggingEvent>(); SqlConnection myConnection = new SqlConnection("Data Source=xxx;user id=xxx;password=xxx;connection timeout=30"); myConnection.Open(); SqlDataReader myReader = null; SqlCommand command = new SqlCommand("SELECT Id,Ts,LogLevel,LoggerName,Message,ThreadName,UserName,ExceptionString,Domain,ClassName,FileName,MethodName,LineNumber,LocalIP,MachinName,UnikeName from dbo.LoggingEvent " + where); command.Connection = myConnection; myReader = command.ExecuteReader(); while (myReader.Read()) { events.Add(LoggingEvent.ReadEntityFromDbReader(myReader)); } myConnection.Close(); return events; } [HttpPost] public ActionResult ReloadGrid(string fromDate, string toDate) { DateTime fromDateTime; DateTime toDateTime; if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate)) // todo { fromDateTime = ParseStringToDate(fromDate); toDateTime = ParseStringToDate(toDate); } else// No dates specified = get last 24 hours { toDateTime = DateTime.Now; fromDateTime = toDateTime.AddHours(-24); } if (fromDateTime.CompareTo(toDateTime) > 0) { // from date grater then todate, change places DateTime temp = toDateTime; toDateTime = fromDateTime; fromDateTime = temp; } DataSource = GetEventsOnDateTime(fromDateTime, toDateTime); return PartialView("_LogView"); } public DateTime ParseStringToDate(string datetxt)// todo this is copy froim treemenuviewcontroller, create utilsclass { const string dateformat = "dd.MM.yyyy HH:mm"; // jquery datepicker const string dateformat2 = "yyyy-MM-dd HH:mm";// chrome TODO different formats with different location setting? DateTime dateTime; try //todo error handling! { dateTime = DateTime.ParseExact(datetxt, dateformat, CultureInfo.InvariantCulture); } catch { dateTime = DateTime.ParseExact(datetxt, dateformat2, CultureInfo.InvariantCulture); } return dateTime; } public ActionResult ExportToPDF() { var printable = GridViewExtension.CreatePrintableObject(GridViewSettings, DataSource); PrintingSystem ps = new PrintingSystem(); PrintableComponentLink link1 = new PrintableComponentLink(ps); link1.Component = printable; link1.PrintingSystem.Document.AutoFitToPagesWidth = 1; link1.Landscape = true; CompositeLink compositeLink = new CompositeLink(ps); compositeLink.Links.Add(link1); compositeLink.CreateDocument(); using (MemoryStream stream = new MemoryStream()) { compositeLink.PrintingSystem.ExportToPdf(stream); WriteToResponse("filename", true, "pdf", stream); } ps.Dispose(); return Index(); } void WriteToResponse(string fileName, bool saveAsFile, string fileFormat, MemoryStream stream) { string disposition = saveAsFile ? "attachment" : "inline"; Response.Clear(); Response.Buffer = false; Response.AppendHeader("Content-Type", string.Format("application/{0}", fileFormat)); Response.AppendHeader("Content-Transfer-Encoding", "binary"); Response.AppendHeader("Content-Disposition", string.Format("{0}; filename={1}.{2}", disposition, fileName, fileFormat)); Response.BinaryWrite(stream.GetBuffer()); Response.End(); } } } Any clues? Ps. Asking me why I don't write to DevExpress support is not helpful, so please just don't comment at all.
Check the How to export GridView rows and keep end-user modifications (such as sorting, grouping, filtering, selection) KB Article and make sure if all the steps are implemented.
After help for #Mikhail i fix the issue by putting #Html.Action("Grid","LogView") in the Html.BeginForm in _Log.View.cshtml like that: <div id="buttonReset" class ="gridBtn"> <input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/> </div> #using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post)) { <div id="buttonExport" class ="gridBtn"> <input type="submit" id ="ExportBtn" value="Export to pdf" /> </div> #Html.Action("Grid","LogView")}
MVC populate drop down list no postback
Is their a way to populate a drop down list by pressing a button without post back. Ex: dropdownlist1 -> a press button and populates dropdownlist2 with different data regarding dropdownlist1 value. Thanks
Most common scenario is generating the second dropdownlist values depending on the first DropDownList selected item changed. I assume that you are looking for the same scenario and below code is for achieve that. Let me know if you really need the button click to generate the second dropdown. Model: namespace MvcApplicationrazor.Models { public class CountryModel { public List<State> StateModel { get; set; } public SelectList FilteredCity { get; set; } } public class State { public int Id { get; set; } public string StateName { get; set; } } public class City { public int Id { get; set; } public int StateId { get; set; } public string CityName { get; set; } } } Controller: public ActionResult Index() { CountryModel objcountrymodel = new CountryModel(); objcountrymodel.StateModel = new List<State>(); objcountrymodel.StateModel = GetAllState(); return View(objcountrymodel); } //Action result for ajax call [HttpPost] public ActionResult GetCityByStaeId(int stateid) { List<City> objcity = new List<City>(); objcity = GetAllCity().Where(m => m.StateId == stateid).ToList(); SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0); return Json(obgcity); } // Collection for state public List<State> GetAllState() { List<State> objstate = new List<State>(); objstate.Add(new State { Id = 0, StateName = "Select State" }); objstate.Add(new State { Id = 1, StateName = "State 1" }); objstate.Add(new State { Id = 2, StateName = "State 2" }); objstate.Add(new State { Id = 3, StateName = "State 3" }); objstate.Add(new State { Id = 4, StateName = "State 4" }); return objstate; } //collection for city public List<City> GetAllCity() { List<City> objcity = new List<City>(); objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" }); objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" }); objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" }); objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" }); objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" }); objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" }); return objcity; } View: #model MvcApplicationrazor.Models.CountryModel #{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> <script language="javascript" type="text/javascript"> function GetCity(_stateId) { var procemessage = "<option value='0'> Please wait...</option>"; $("#ddlcity").html(procemessage).show(); var url = "/Test/GetCityByStaeId/"; $.ajax({ url: url, data: { stateid: _stateId }, cache: false, type: "POST", success: function (data) { var markup = "<option value='0'>Select City</option>"; for (var x = 0; x < data.length; x++) { markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>"; } $("#ddlcity").html(markup).show(); }, error: function (reponse) { alert("error : " + reponse); } }); } </script> <h4> MVC Cascading Dropdown List Using Jquery</h4> #using (Html.BeginForm()) { #Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { #id = "ddlstate", #style = "width:200px;", #onchange = "javascript:GetCity(this.value);" }) <br /> <br /> <select id="ddlcity" name="ddlcity" style="width: 200px"> </select> <br /><br /> }
Second DDL not firing
good day, why my second DDL do not fire when I select the Parent dropdown list. Also can anyone elaborate the script and the [ 0] in the View beside m=>m.StateModel And for the last question, how can I make this DDL dynamic, How can I populate it using database data? Model using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Kaskid.Models { public class State { public int Id { get; set; } public string StateName { get; set; } } public class City { public int Id { get; set; } public int StateId { get; set; } public string CityName { get; set; } } public class CountryModel { public List<State> StateModel { get; set; } public SelectList FilteredCity { get; set; } } } Controller using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Kaskid.Models; namespace Kaskid.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { CountryModel objCountryModel = new CountryModel(); objCountryModel.StateModel = new List<State>(); objCountryModel.StateModel = GetAllState(); return View(objCountryModel); } [HttpPost] public ActionResult GetCityByStateId(int stateId) { List<City> objCity = new List<City>(); objCity = GetAllcity().Where(m => m.StateId == stateId).ToList(); SelectList obgcity = new SelectList(objCity, "Id", "CityName", 0); return Json(obgcity); } public List<State> GetAllState() { List<State> objState = new List<State>(); objState.Add(new State {Id = 0,StateName="Select State"}); objState.Add(new State {Id = 1,StateName = "State 1"}); objState.Add(new State {Id = 2, StateName="State 2"}); objState.Add(new State {Id = 3, StateName="State 3"}); return objState; } public List<City> GetAllcity() { List<City> objCity = new List<City>(); objCity.Add(new City{Id = 1,StateId = 1, CityName = "City1-1" }); objCity.Add(new City{Id = 2,StateId=2,CityName = "City2-1"}); objCity.Add(new City{Id = 3,StateId=4,CityName="City4-1"}); objCity.Add(new City{Id = 4,StateId=1,CityName="City1-2"}); return objCity; } } } View #model Kaskid.Models.CountryModel #{ ViewBag.Title = "Index"; } <script language="javascript"> function GetCity(_stateId) { var procemessage = "<option value='0'> Please wait...</option>"; $('#ddlcity').html(procemessage).show(); var url = "/Home/GetCityByStaeId/"; $.ajax({ url: url, data: { stateid: _stateId }, cache: false, type: "POST", success: function (data) { var markup = "<option value='0'>Select City</option>"; for (var x = 0; x < data.length; x++) { markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>"; } $('#ddlcity').html(markup).show(); }, error: function (reponse) { alert("error : " + reponse); } }); } </script> <h4> MVC3 Cascading Dropdown List Using Jquery</h4> #using (Html.BeginForm("", "")) { #Html.DropDownListFor(m => m.StateModel[0].Id, new SelectList(Model.StateModel, "Id", "StateName"), new { #id = "ddlstate", #style = "width:200px;", #onchange = "javascript:GetCity(this.value);" }) <br /> <br /> <select id="ddlcity" name="ddlcity" style="width: 200px"> </select> }
You've got a typo: var url = "/Home/GetCityByStaeId/"; But your controller action is called GetCityByStateId and not GetCityByStaeId. Also you may take a look at a similar example I once wrote where you could take some ideas about improving your code.