2012-03-10 2 views
0

Мой вопрос в том, как присвоить данные таблицы любой переменной. Я попросил вернуть забытый пароль сотрудника через его адрес электронной почты, введенный в текстовое поле, и отправить его ему почта счет .. я уже получает данные, но не знаю, как назначить этот пароль в теле письмаИзвлечь значение из базы данных и присвоить ее любой переменной

мой код здесь

Модель

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; 

namespace TelerikLogin.Models.ViewModels 
{ 
    public class ForgotPassword 
    { 
     public int user_id { get; set; } 
     public string user_login_name { get; set; } 
     public string user_password { get; set; } 

     [Required] 
     [Display(Name="Email Address : ")] 
     public string user_email_address { get; set; } 
    } 
} 

Просмотр

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TelerikLogin.Models.ViewModels.ForgotPassword>" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    ForgotPassword 
</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

<h2>ForgotPassword</h2> 
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script> 
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script> 

<% using (Html.BeginForm("ForgotPassword", "Account", FormMethod.Post)) 
    { %> 

    <%: Html.LabelFor(m => m.user_email_address) %> 
    <%: Html.TextBox("user_email_address")%> 
     <%: Html.ValidationSummary(true) %> 

<input type="submit" value="Submit"/> 

Контроллер

public ActionResult ForgotPassword() 
{ 
    return View(); 
} 

[HttpPost] 
public ActionResult ForgotPassword(string user_email_address) 
{ 


    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\MVC3\TelerikLogin\TelerikLogin\App_Data\Login.mdf;Integrated Security=True;User Instance=True"); 

    DataTable dt1 = new DataTable(); 

    string strQuery = string.Format("SELECT user_password FROM [user_master] WHERE user_email_address='{0}'",user_email_address); 



    conn.Open(); 

    SqlDataAdapter da1 = new SqlDataAdapter(strQuery, conn); 
    da1.Fill(dt1); 

    LoginEntities3 le= new LoginEntities3(); 

    conn.Close(); 

//...... Below is the query where i fetch the password in var pwd 

    var pwd = from u in new LoginEntities3().user_master 
       where u.user_email_address == user_email_address select u.user_password; 




    if (dt1.Rows.Count > 0) 
    { 


     MailAddress mailfrom = new MailAddress("[email protected]"); 
     MailAddress mailto = new MailAddress(user_email_address); 
     MailMessage newmsg = new MailMessage(mailfrom, mailto); 

     newmsg.Subject = "Your Password"; 

**// Here i assign pwd to messege body then it gives an error of type casting so i converted it in To string** 

     newmsg.Body = pwd.ToString(); 



     SmtpClient smtps = new SmtpClient("smtp.gmail.com", 587); 
     smtps.UseDefaultCredentials = false; 
     smtps.Credentials = new NetworkCredential("[email protected]", "password"); 
     smtps.EnableSsl = true; 
     smtps.Send(newmsg); 


     return RedirectToAction("About", "Home"); 
    } 


    return View(); 
} 

В newmsg.body я присвоить переменной PWD (который принес пароль пользователя), то он дает мне ошибку типа литья так Я использую метод String() , поэтому он отправляет запрос sql без пароля в тело msg. Итак, как это сделать?

+0

Не могли бы вы отладить и проверить, что такое значение для «pwd»? – Manas

+0

Я думаю, вам нужно использовать singleordefault для выбранного запроса LINQ http://msdn.microsoft.com/en-us/library/bb359429.aspx –

+0

@Manas oh okey i debug it .. и он отображает только выражение, подобное этим ((System.Data.Objects.ObjectQuery) (pwd)) – Dip

ответ

0

Try This

строку PWD = (от и в новом LoginEntities3() user_master где u.user_email_address == USER_EMAIL_ADDRESS выбрать u.user_password.) .ToString();

Смежные вопросы