returning data from controller to VIEW - asp.net-mvc

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>

Related

MVC gridview return popup with html when select filter or click next page

mvc gridview return popup with html when select filter or click next page how can I fix this problem in this code show my partial gridview my view and controller action
PartialView
#{
Html.DevExpress().GridView(settings =>
{
settings.Name = "TestList";
settings.CallbackRouteValues = new { Controller = "Admin", Action = "TestList" };
settings.CommandColumn.Visible = true;
settings.KeyFieldName = "ID";
settings.CommandColumn.Visible = false;
settings.Columns.Add(column =>
{
column.Caption = "Edit";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Edit", "TestListEdit", "admin",
new { id = content.KeyValue }, null)));
});
settings.Columns.Add(column =>
{
column.Caption = "Delete";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Delete", "TestListDelete", "admin",
new { id = content.KeyValue }, null)));
});
settings.Columns.Add(column =>
{
column.Caption = "Manage";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Manage Questions", "ManageQuestions", "admin",
new { id = content.KeyValue }, null)));
});
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.Columns.Add("ID");
settings.Columns.Add("Title");
settings.Columns.Add("Description");
settings.Columns.Add("Lang_ID");
settings.Columns.Add("TryDescription");
}).Bind(Model).Render();
}
this is my View
#model List<FastCreditTraining.Models.AdminTestListEditingModel>
#{
ViewBag.Title = "TestList";
Layout = "~/Views/Shared/_adminLayout.cshtml";
}
#{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "English",
Value = "1"
});
listItems.Add(new SelectListItem
{
Text = "Հայերեն",
Value = "2",
});
}
<body>
<div style="display:inline-block;float:right; margin-right:30px; margin-top:10px">
#Html.ActionLink("Create", "TestListCreate", "admin", new { #class = "LangButton" })
</div>
<div style="display:inline-block">
<form style="display:inline-block" name="tActive" id="tActive" method="get">
<div style="margin-left:50px; display:inline-block;">
<p style="display:inline-block">#Resources.Resource.DisplayActiveTests</p>
#Html.CheckBox("tActive", true)
</div>
<div style="margin-left:100px; display:inline-block;">
<p style="display:inline-block">#Resources.Resource.SetLanguageInterfaceEdit</p>
#Html.DropDownList("langSwitch", listItems)
</div>
<input type="submit" name=" asdasd" value="Filter">
</form>
</div></body>
#{Html.RenderPartial("_GridViewTestListPartial",Model);}
And this is my controller action
![\[Authorize\]
public ActionResult TestList(string tActive, string langSwitch)
{
//tActive and langSwitch choose getting tests with procedure getTests_Result
List model1;
if (tActive == null || langSwitch == null)
{
model1 = db.getTests(true, 1).ToList();
}
else
{
model1 = db.getTests(Convert.ToBoolean(tActive), Convert.ToInt32(langSwitch)).ToList();
}
///////////////////end of getting///////////////////
// Fill new created model from database test lists and departaments and positions
List _Departments = db.T_Department_Lang.ToList();
List _Positions = db.T_Position_Lang.ToList();
List _checkForDep = new List();
List _checkForPos = new List();
foreach (var item in _Departments)
{
_checkForDep.Add(new bool());
}
foreach (var item in _Positions)
{
_checkForPos.Add(new bool());
}
for (int i = 0; i < model1.Count; i++)
{
allModels.Add(new AdminTestListEditingModel()
{
ID = model1\[i\].ID,
Date_Added = model1\[i\].Date_Added,
Limit = model1\[i\].Limit,
IS_Active = model1\[i\].IS_Active,
Allow_Back = model1\[i\].Allow_Back,
Title = model1\[i\].Title,
Description = model1\[i\].Description,
Lang_ID = model1\[i\].Lang_ID,
S_Changed = model1\[i\].S_Changed,
Question_qnt = model1\[i\].Question_qnt,
Pos_Save = model1\[i\].Pos_Save,
Question_test_qnt = model1\[i\].Question_test_qnt,
TryDescription = model1\[i\].TryDescription,
qCount = model1\[i\].qCount,
TestList_Id = model1\[i\].ID,
Departments = _Departments,
Positions = _Positions,
checkForDep = _checkForDep,
checkForPos = _checkForPos
});
}
//////////////// end fill //////////////////
Session\["allModels"\] = allModels;
return View(allModels);
}][1]
Return PartialView instead of View to resolve this issue:
//return View(allModels);
return PartialView(allModels);
See the Why can the alert message with the HTML/JavaScript/CSS content appear when using callback-aware extensions? knowledge resource to learn more.

MVC Model in the View not Updating

I've got a very basic MVC project that does maths operations (+ - / *) of 2 numbers
for some reasons my view is not updating after postback
here is my controller
namespace MathsAppMVC.Controllers
{
public class HomeController : Controller
{
MathsServiceClient loClient = new MathsServiceClient();
Int32 loNum1 = 0;
Int32 loNum2 = 0;
//Int32 result = 0;
String locOperation = "Add";
public ActionResult Index()
{
var model = new MathsModel
{
Number1 = loNum1,
Number2 = loNum2,
//Result = result,
MathsOperation = locOperation
};
return View(model);
}
[HttpGet]
public ActionResult MathsOperation()
{
return View();
}
[HttpPost]
public ActionResult MathsOperation(MathsModel mathsModel)
{
loNum1 = mathsModel.Number1;
loNum2 = mathsModel.Number2;
locOperation = mathsModel.MathsOperation;
if (locOperation == "Add")
{
mathsModel.Result = loClient.add(loNum1, loNum2);
}
else if (locOperation == "Subtract")
{
mathsModel.Result = loClient.subtract(loNum1, loNum2);
}
else if (locOperation == "Multiple")
{
mathsModel.Result = loClient.multiple(loNum1, loNum2);
}
else
if (locOperation == "Divide")
{
mathsModel.Result = loClient.divide(loNum1, loNum2);
}
if (ModelState.IsValid)
{
return View("Index", mathsModel);
}
else
{
return View("Index");
}
}
}
}
HERE IS VIEW
#model MathsAppMVC.Models.MathsModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("MathsOperation", "Home", FormMethod.Post, new { }))
{
<fieldset>
<legend>Maths:</legend>
<div>#Html.LabelFor(u=>u.MathsOperation)</div>
<div>#Html.DropDownListFor(u => u.MathsOperation, new SelectList(
new List<Object>
{
new { value = "Add" , text = "Add" },
new { value = "Subtract" , text = "Subtract" },
new { value = "Multiple" , text = "Multiple"},
new { value = "Divide" , text = "Divide"}
},
"value",
"text",
0))
</div>
<div>#Html.LabelFor(u=>u.Number1)</div>
<div>#Html.TextBoxFor(u=>u.Number1)</div>
<div>#Html.LabelFor(u=>u.Number2)</div>
<div>#Html.TextBoxFor(u=>u.Number2)</div>
<div>#Html.LabelFor(u=>u.Result)</div>
<div>#Html.DisplayTextFor(u=>u.Result)</div>
<input type="submit" value ="Calculate" />
<input type="reset" value ="Clear" />
</fieldset>
}
In the view after postback for what ever reason the Result is always 0.
Some one please help?
I hate to post this as an answer, but that's all I can do with my amount of reputation. I literally copied and pasted your code into a new MVC project and it works fine. Can you post your MathsServiceClient code?

dropdownlistfor produce system.nullreferenceException

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.

how to generate new row in webgrid on asp.net mvc4

I am having Text Box and a Button.I need to add Text Box value in Web grid when button was clicked.I coded to add text box value in grid but in the same column cell the value will be updated. I need to generate new column and add values ...
Index.cshtml Code
#{
#Html.TextBox("Value", "", new { id = "txtid" })
<input type="button" value="Submit" onclick="onSelectedIndexChanged()" id="btn" />
WebGrid grid = new WebGrid(Model, selectionFieldName: "SelectedRow");
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Edit", header: null, format: #<text>#item.GetSelectLink("Edit")</text>),
grid.Column("Firstname", format: #<text>#item.GivenName</text>),
grid.Column("Surname", format: #<text>#item.Surname</text>),
grid.Column("Age", format: #<text>#item.Age</text>)
)
)
}
Models Code:
People.cs
public ObservableCollection<People> GetCustomerList(string firstname)
{
ObservableCollection<People> CustomerList = new ObservableCollection<People>();
DataTable dtCustomer = new DataTable();
CustomerList.Add(new People { Id = i, GivenName = firstname, Surname = "Kumar", Age = 25 });
i++;
return CustomerList;
}
Controller Code:
Home Controller.cs
public ActionResult GetPeople(string firstname)
{
//List<People> ItemList = new List<People>();
// ViewBag.Items = ItemList;
ObservableCollection<People> ItemList = new ObservableCollection<People>();
People Customer = new Models.People();
ItemList = Customer.GetCustomerList(firstname);
return PartialView("Index", ItemList);
}

Object reference not set to an instance of an object for dropdownlist in model

I have no idea why this is happening, I have set the values and debugged it, but it is just not passing the information from the controller to the view. Here is what is going on
Model:
public class QueueFilterModel
{
public string SelectedFilter { get; set; }
public string query { get; set; }
public List<string> MyFilterList { get; set; }
}
Controller:
[HttpGet]
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View();
}
View:
#model RazorARPP.Models.QueueFilterModel
#{
ViewBag.Title = "Queue";
}
<h2>Queue</h2>
<form action="" method="post" enctype="multipart/form-data" id="MyForm">
Filter
<div>
Filter Options:
</div>
<div>
#Html.DropDownList("test", new SelectList(Model.MyFilterList,Model.SelectedFilter))
</div>
<h3>Insert Instructions Here</h3>
#{
var DB = Database.Open("CHAVI");
var grid = new WebGrid(DB.Query("SELECT * FROM [TicketQueue]"), null, null, 20);
#grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column(header: "Link", style: "labelcolumn", format: (item) => Html.ActionLink("Edit Item", "EditQueue", new { id = item.QueueID})),
grid.Column("Description", "Description"),
grid.Column("QueueDate", "QueueDate"),
grid.Column("Note", "Note"),
grid.Column("Status", "Status"),
grid.Column("LastUpdated", "LastUpdated")
)
)
}
</form>
The grid part is working fine (and the query). The problem is in the dropdown, it isn't set to anything there. Any thoughts? Thanks.
Are you not passing the model to view?
Should it not be
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View(model);
}
Try using:-
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View(model);
}

Resources