dropdownlistfor produce system.nullreferenceException - asp.net-mvc

I'm trying to create a webpage to send text msg to phone. I'm having trouble getting the carrier drop down list right. It always tells me that "an exception of type 'System.NullReferenceException' occurred in App_Web_ucvryg25.dll but was not handled in user code" when I try to run the code.
Here is my view:
#model MVCTesting2.Models.MailModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<fieldset>
<legend>
Send Text
</legend>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>Phone number: </p>
<p>#Html.TextBoxFor(m => m.To)</p>
<p>Carriers</p>
<p>#Html.DropDownListFor(m => m.Carrier,
new SelectList(
new List<Object>{
new { value = "#text.att.net" , text = "att" },
new { value = "#cingularme.com" , text = "cingular" },
new { value = "#messaging.nextel.com" , text = "nextel"}
},
"value",
"text",
Model.Carrier))</p>
<p>Subject: </p>
<p>#Html.TextBoxFor(m => m.Subject)</p>
<p>Body: </p>
<p>#Html.TextAreaFor(m => m.Body)</p>
<input type="submit" value="Send" />
}
</fieldset>
Here is my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
namespace MVCTesting2.Controllers
{
public class SendTextController : Controller
{
//
// GET: /SendText/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(MVCTesting2.Models.MailModel _objModelMail)
{
if (ModelState.IsValid)
{
string from = "myemail";
string to = _objModelMail.To;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, _objModelMail.From, System.Text.Encoding.UTF8);
mail.Subject = _objModelMail.Subject;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = _objModelMail.Body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "mypassword");
client.Port = 587; // Gmail works on this port<o:p />
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
client.Send(mail);
return View("Send");
}
else
{
return View();
}
}
}
}
The model is pretty simple with all the variables.
Any idea why this happened?
Thanks in advance!

You are binding the dropdown list with m=>m.carrier why again you are mentioning Model.Carrier. It is not required , remove it.
And use some thing like this:
#Html.DropDownListFor(m => m.Carrier,
new SelectList(
new List<Object>{
new { value = "#text.att.net" , text = "att" },
new { value = "#cingularme.com" , text = "cingular" },
new { value = "#messaging.nextel.com" , text = "nextel"}
},
"value",
"text"));
Hope this helps...

Looks like you're using Model.Carrier as value for the SelectedValue parameter in the DropDownListFor.
Either you remove Model.Carrier or you put a value in it.

Related

DropDownListFor Razor with List<string>

using (Html.BeginForm("Add", "Test", new { profil = Model.SelectedProfil }, FormMethod.Post))
{
#Html.DropDownListFor(m => m.SelectedProfil, new SelectList(Model.Profils.Select(x => new { Value = x, Text = x }),"Value","Text"))
<button type="submit">Add</button>
}
Profils = List of string
SelectedProfil = string
SelectedProfil is always null to the controller on post
Simply
using (Html.BeginForm("Add", "Test", FormMethod.Post))
#Html.DropDownList("profil", new SelectList(Model.Profils.Select(x => new { Value = x, Text = x }),"Value","Text")))
[HttpPost]
public ActionResult Add(string profil)
{
....
}

returning data from controller to VIEW

ii am told to create a login system in MVC 3 using old traditional sql queries etc, i have created login but problem is that i'm returning data from model to View . I have created datatable in model and returning it to controller, successfully but don't know that how to show that data on view ? have searched good but didn't help.
MODEL :
public ConnectionStatus Login_db(String email, String pwd, String conStr)
{
String hashedpwd_login = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "SHA1");
using (SqlConnection sqlCon = new SqlConnection(conStr))
{
using (SqlCommand sqlCom = new SqlCommand())
{
sqlCom.Connection = sqlCon;
sqlCom.CommandText = "select Count(*) from tblRegister where userEmail=#email AND userPwd=#pwd";
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", hashedpwd_login);
String select_com = "select * from tblRegister";
SqlCommand sqlCom2 = new SqlCommand(select_com, sqlCon);
ConnectionStatus connectStatus = new ConnectionStatus();
int no_rows_affected;
SqlDataAdapter sda = new SqlDataAdapter(select_com, sqlCon);
DataTable data_tb = new DataTable();
try
{
sqlCon.Open();
no_rows_affected = Convert.ToInt32(sqlCom.ExecuteScalar());
if (no_rows_affected == 1)
{
connectStatus.Message = "User logged in successfully, " + no_rows_affected;
sda.Fill(data_tb);
tableCreation tb_creation = new tableCreation();
tb_creation.CreateTable = data_tb;
}
else
{
connectStatus.Message = "Invalid email/password combination.";
}
}
catch (Exception ex)
{
connectStatus.Message = ex.Message;
}
return connectStatus;
}
}
}
Controller :
public ActionResult loginResult(String command, FormCollection formData)
{
if (command == "Login")
{
var email = formData["txtboxEmail"];
var pwd = formData["txtboxPassword"];
// String conStr = "Data Source=HUNAIN-PC;Initial Catalog=registration;User ID=sa;Password=abc123!##";
database model_db = new database();
var db_status = model_db.Login_db(email, pwd, conStr);
ViewBag.Message = db_status.Message;
}
tableCreation retTable = new tableCreation();
return View(retTable.CreateTable);
}
View:
#{
ViewBag.Title = "Login Authentication";
}
<h2>Login Authentication</h2>
<h4>#ViewBag.Message</h4>
Note: some classes are user defined for multi purposes.
You can use WebGrid in MVC3. This is new in MVC3. Use this code in your View.
#model IList<YourViewModel>
#{
ViewBag.Title = "Login Information";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{
var grid = new WebGrid(source: Model, rowsPerPage: 200,
canPage: false, canSort: true, defaultSort: "Absentee");
}
<p>
<h2>Absentee List</h2>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column(format: (item) => Html.ActionLink("Edit", "Edit",
new { id = item.Id })),
grid.Column("Absentee", "Absentee",canSort:true),
grid.Column("AbsStart", "AbsStartDate")
))
</div>
</p>

i get Error executing child request for handler

my LogIn is partial view. i pass a model that contain some fields of tbl_profile to partial view and fill it and then i pass filled model to a actionresult in [HttpPost] part and ...
but now i'm trouble in [HttpGet] part . i get this error on this line of cod " *#Html.Action("LogOn","Account")"*.
my code :
[HttpGet]
public ActionResult LogOn(string returnUrl)
{
using (var db = new MyContext())
{
var AllFeatureToLog = db.tbl_profile.Select(u => new UsersClass.LogOn { username = u.username, password_User = u.password_User }).ToList();
return PartialView(AllFeatureToLog);
}
}
class:
public class UsersClass
{
public class LogOn
{
public string username { get; set; }
public string password_User { get; set; }
}
}
LogOn.cshtml:
#model MyProject.Models.UsersClass.LogOn
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<form class="signin-form">
#Html.TextBoxFor(m => m.username, new { #id = "username", #class = "input-block- level", #placeholder = "* enter username" })
#Html.TextBoxFor(m => m.password_User, new { #id = "password", #class = "input-block-level", #placeholder = "* enter pass" })
#Html.ValidationMessage("LoginError")
<label class="checkbox">
<input type="checkbox">remember me</label>
<button class="btn btn-medium btn-general input-block-level" type="submit"> enter</button>
</form>
}
error:
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'
Use this instead ::
#{ Html.RenderAction("LogOn","Account"); }
This will fix your issue.
You sending List:
var AllFeatureToLog = db.tbl_profile.Select(u => new UsersClass.LogOn { username = u.username, password_User = u.password_User }).ToList();
return PartialView(AllFeatureToLog);
But your View expectiong only one model:
#model MyProject.Models.UsersClass.LogOn
Change: your ActionResult on sending one: var AllFeatureToLog = db.tbl_profile.Select(u => new UsersClass.LogOn { username = u.username, password_User = u.password_User }).Fist();
or View for getting List: #model IENumerable<MyProject.Models.UsersClass.LogOn>

asp.net mvc Send form from site to email

I have feedback form on my mvc site, it looks like
I created model for my form
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ComponentTrading.Web.Models
{
public class FeedbackForm
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
}
}
I created view for my form
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "contact-form" }))
{
<fieldset>
#Html.TextBoxFor(model => model.Name, new { #Value = "Name" })
#Html.TextBoxFor(model => model.Email, new { #Value = "E-mail" })
#Html.TextBoxFor(model => model.Phone, new { #Value = "Phone" })
#Html.TextAreaFor(model => model.Message, new { #class = "img-shadow"})
<input class="form-button" data-type="reset" value="Clear" />
<input class="form-button" data-type="submit" type="submit" value="Send" />
}
and now i try to do a sending a letter to email, but it doesn work, when I push "send-button" it happens nothing and I dont get email
my controller
[HttpGet]
public ActionResult Contacts()
{
FeedbackForm temp = new FeedbackForm();
temp.Message = "Message";
return View(temp);
}
[HttpPost]
public ActionResult Contacts(FeedbackForm Model)
{
string Text = "<html> <head> </head>" +
" <body style= \" font-size:12px; font-family: Arial\">"+
Model.Message+
"</body></html>";
SendEmail("mironny#inbox.ru", Text);
FeedbackForm temp = new FeedbackForm();
return View(temp);
}
public static bool SendEmail(string SentTo, string Text)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("Test#mail.ru");
msg.To.Add(SentTo);
msg.Subject = "Password";
msg.Body = Text;
msg.Priority = MailPriority.High;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.mail.ru", 25);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
client.Credentials = new NetworkCredential("TestLogin", "TestPassword");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception)
{
return false;
}
return true;
}
what's wrong?
Use
// if you dont pass any parameter
// BeginForm posted to the action that
// has name as view name.
// so no need to write any parameters
#using (Html.BeginForm())
{
...
<input type="submit" value="Send">
}
OR
#using (Html.BeginForm("Contacts", "SomeController", FormMethod.Post, new { id = "contact-form" }))
{
...
<input type="submit" value="Send">
}
You have a few question about mvc and there is more important thing of them is incorrect overload methods. My suggestion, first, you should learn html-helpers overload methods. And MVC model binding strategies...

ASP MVC: Sending an E-mail and return Message (No Json)

I have a doubt have a project done in ASP.NET MVC 3, where there is a contact form. It works perfectly the problem is that I want to put a message "Email Sent successfully!" to complete your submission. I'm not using Json. What would be the most appropriate solution
Thank you!
the code:
Contato.cshtml
`
#model SSInstitucional.ViewModel.ContatoViewModel
#using System.Web
<link href="../../Content/themes/SCTecno.css" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("EnviaEmail"))
{
#Html.ValidationSummary(true, "")
<div id ="divContato" style="text-align:left; margin-left:460px; margin-right:400px; font-family:Verdana;">
<div id="txtNome" class="editor-label">
#Html.LabelFor(model => model.Nome)
<p>
#Html.TextBoxFor(m => m.Nome, new { id = "Nome", size = 40, maxlength = "60" })
#Html.ValidationMessageFor(model => model.Nome)
</div>
<div id="txtEmail" class="editor-field">
#Html.LabelFor(model => model.Email)
<p>
#Html.TextBoxFor(m => m.Email, new { id = "Email", size = 40, maxlength = "200" })
#Html.ValidationMessageFor(model => model.Email)
</div>
<div id="txtAssunto"class="editor-label">
#Html.LabelFor(model => model.Assunto)
<p>
#Html.TextBoxFor(m => m.Assunto, new { id = "assunto", size = 40, maxlength = "200" })
#Html.ValidationMessageFor(model => model.Assunto)
</div>
<div id="txtMensagem" class="editor-field">
#Html.LabelFor(model => model.Mensagem)
<p>
#Html.TextAreaFor(model => model.Mensagem, new { id = "mensagem", rows = "10", cols = "50", maxlength = "5000" })
#Html.ValidationMessageFor(model => model.Mensagem)
</div>
<div id="Enviar" onClick="alert('E-mail enviado com sucesso!!')")>
#SSHtml.SubmitStyledButton("Enviar")
</div>
</div>
}
`
ContatoController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSInstitucional.ViewModel;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
using System.Diagnostics;
namespace SSInstitucional.Controllers
{
public class ContatoController : Controller
{
//
// GET: /Contato/
public ActionResult Index()
{
return View();
Debug.WriteLine("Debug Teste");
}
[HttpPost]
public ActionResult Index(ContatoViewModel contatoViewModel)
{
string corpo = "Nome: " + contatoViewModel.Nome + "\n" +
"E-Mail: " + contatoViewModel.Email + "\n" +
"Assunto: " + contatoViewModel.Assunto + "\n\n" +
contatoViewModel.Mensagem;
sendEmail(contatoViewModel.Nome, contatoViewModel.Email, contatoViewModel.Assunto, corpo);
// return Json ( new { Sucess = true, MessageBox = "Email enviado com sucesso!" });
// return Json (new { mbox = "E-Mail enviado com sucesso!" });
return View();
}
public ActionResult EnviaEmail()
{
return View();
}
private void sendEmail(string fromName, string FromEmail, string subject, string body)
{
try
{
string smtpEmail = null;
string usuarioEmail = null;
string senhaEmail = null;
int smtpPort = 0;
bool enableSsl = false;
MailMessage mail = new MailMessage();
////set the addresses
mail.From = new MailAddress(FromEmail, fromName);
mail.Sender = new MailAddress(FromEmail, fromName);
mail.ReplyTo = new MailAddress(FromEmail, fromName);
mail.To.Add(new MailAddress("myname#webmail.net", fromName));
//set the content
mail.Subject = subject;
mail.Body = body;
mail.Body += "\n\n------------------------------------------";
mail.Body += "\n\nEmail de origem: " + FromEmail;
mail.Body += "\n\n\nEmail enviado pelo Fale Conosco do site.";
//send the message
//SmtpClient smtp = new SmtpClient(smtpEmail);
SmtpClient smtp = new SmtpClient("smtp.webmail.net");
NetworkCredential credenciais = new NetworkCredential("contato#webmail.net", "sss1122");
smtp.Credentials = credenciais;
//smtp.Port = 587;
if (smtpPort > 0)
smtp.Port = 25;
// enable SSL
if (enableSsl)
smtp.EnableSsl = true;
smtp.Timeout = 120000;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
{
ModelState.Clear();
//return mail(new { Message = "E-mail enviado com sucesso!" });
}
}
catch (FormatException erroFormato)
{
throw new Exception("Falha ao enviar email. Verifique se seu email foi digitado corretamente.");
}
catch (Exception erro)
{
throw new Exception("Falha ao enviar email.");
}
}
}
}
If you can use js, you could use a MVC Ajax form. A example is here http://www.hanselman.com/blog/ASPNETMVCPreview4UsingAjaxAndAjaxForm.aspx
You just need replace
#using (Html.BeginForm("EnviaEmail"))
{
....
}
with
#using(Ajax.BeginForm("EnviaEmail", new AjaxOptions
{
UpdateTargetId = "form_wrapper_id",
InsertionMode = InsertionMode.Replace
}))
{
...
}
and return from Action some massage. This message will be put to HTML tag with id 'form_wrapper_id'. If you can't use js the answer by Darin Dimitrov is the best.
Your form is currently pointing to the EnviaEmail controller action. The EnviaEmail controller action doesn't do anything. It only redisplays the view. It doesn't send any email whatsoever. So I guess that your original code is actually pointing to the Index POST action:
#using (Html.BeginForm())
{
...
}
From what I can see in your code this POST action sends an email and redisplays the same view. So once the email is sent you could store some message in the ViewBag:
[HttpPost]
public ActionResult Index(ContatoViewModel contatoViewModel)
{
string corpo = "Nome: " + contatoViewModel.Nome + "\n" +
"E-Mail: " + contatoViewModel.Email + "\n" +
"Assunto: " + contatoViewModel.Assunto + "\n\n" +
contatoViewModel.Mensagem;
sendEmail(contatoViewModel.Nome, contatoViewModel.Email, contatoViewModel.Assunto, corpo);
ViewBag.Message = "Email sent successfully";
return View();
}
and then in your view display this message:
<div>#ViewBag.Message</div>

Resources