I have 2 form in the single view and below are the code.
#model MCRP.Models.tblRequest
#{
ViewBag.Title = "Review Request";
}
#using (Html.BeginForm("InsertForm", "Home"))
{
#Html.EditorFor(model => model.ContactEmailAddress, new { htmlAttributes = new {id = "txtdelivery"} })
<input type="submit" onclick="return validate();" value="submit" id="submitfilteration" class="btn btn-primary pull-left" />
}
#using (Html.BeginForm("Delete", "Home"))
{
Are you sure you want to delete Property ?
<input type="submit" value="Delete" class="btn btn-danger" />
}
But on click of delete button, the text inserted in the txtdelivery get disappear
Controller
public ActionResult ReviewRequest()
{
if (Session["AddtoCart"] != null)
{
DataTable dt = (DataTable)Session["AddtoCart"];
if (dt.Rows.Count > 0)
{
ViewBag.addedtocart = (DataTable)Session["AddtoCart"];
}
else
{
ViewBag.addedtocart = null;
ViewBag.EmptyCart = "Your Cart Is empty";
}
}
else
{
ViewBag.addedtocart = null;
ViewBag.EmptyCart = "Your Cart Is empty";
}
return View();
}
public ActionResult InsertForm(tblRequest Request)
{
int requestid = 0;
int RequestProperty = 0;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("InsUpsDelTbl_Request"))
{
try
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("#Operation", "InsertRequest");
cmd.Parameters.AddWithValue("#AgencyName", Request.AgencyName);
cmd.Parameters.AddWithValue("#Contact", Request.Contact);
cmd.Parameters.AddWithValue("#DeliveryAddress", Request.DeliveryAddress);
cmd.Parameters.AddWithValue("#ContactPhone", Request.ContactPhone);
cmd.Parameters.AddWithValue("#ContactEmailAddress", Request.ContactEmailAddress);
cmd.Parameters.AddWithValue("#Notes", Request.Notes);
requestid = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
catch (Exception ex)
{ throw ex; }
}
using (SqlCommand cmd = new SqlCommand("InsUpsDelTbl_Request"))
{
DataTable dt = new DataTable();
dt = (DataTable)Session["AddtoCart"];
try
{
if (dt.Rows.Count > 0)
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
for (int i = 0; i < dt.Rows.Count; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Operation", "InsertRequestProperty");
cmd.Parameters.AddWithValue("#RequestID", requestid);
cmd.Parameters.AddWithValue("#PropertyID", dt.Rows[i]["PropertyId"].ToString());
cmd.Parameters.AddWithValue("#Quantity", dt.Rows[i]["Quantity"].ToString());
RequestProperty= Convert.ToInt32(cmd.ExecuteScalar());
}
con.Close();
if (requestid > 0 && RequestProperty>0)
{
TempData["InsertRequestProperty"] = ConfigurationManager.AppSettings["RequestAdded"].ToString().Replace("{#requestid}", Convert.ToString(requestid));
Session["AddtoCart"] = null;
}
}
}
catch (Exception ex)
{ throw ex; }
}
}
return RedirectToAction("ReviewRequest");
}
public ActionResult Delete(FormCollection property)
{
string PropertyID = "";
foreach (var key in property.AllKeys)
{
PropertyID = property["hddeleteGroupid"];
}
DataTable dt = new DataTable();
if (Session["AddtoCart"] != null)
{
dt = (DataTable)Session["AddtoCart"];
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr[0].ToString() == PropertyID)
{
dt.Rows.Remove(dr);
}
}
Session["AddtoCart"] = dt;
}
return RedirectToAction("ReviewRequest");
}
As I am new in MVC I don't know please help me out
More Detail My page more detail is as shown in figure
Now on click of delete one popup with delete dialog gets open and on pressing of delete button one item added in the cart get deleted and also the text inserted in textbox get disappear,
Related
This error appears when I'm training to post reply message and insert it in Replies Table using message id , I think the problem from the View when the id is calling
#using (Html.BeginForm("ReplyMessage", "Messages", FormMethod.Post, new
{ id = "form-reply-message", messageId = #ViewBag.MessageId }))
Any idea what I should change
Controller Get Method:
public ActionResult ReplyMessage(int? Id, int? page)
{
MessageReplyViewModel vm = new MessageReplyViewModel();
if (Id != null)
{
var replies = dbContext.Replies.Where(x => x.MessageId == Id.Value).OrderByDescending(x => x.ReplyDateTime).ToList();
if (replies != null)
{
foreach (var rep in replies)
{
MessageReplyViewModel.MessageReply reply = new MessageReplyViewModel.MessageReply();
reply.MessageId = rep.MessageId;
reply.Id = rep.Id;
reply.ReplyMessage = rep.ReplyMessage;
reply.ReplyDateTime = rep.ReplyDateTime;
reply.MessageDetails = dbContext.Messages.Where(x => x.Id == rep.MessageId).Select(s => s.MessageToPost).FirstOrDefault();
reply.ReplyFrom = rep.ReplyFrom;
vm.Replies.Add(reply);
}
}
else
{
vm.Replies.Add(null);
}
ViewBag.MessageId = Id.Value;
}
return View(vm);
Controller PostMethod :
[HttpPost]
[Authorize]
public ActionResult ReplyMessage(MessageReplyViewModel vm, int messageId)
{
if (vm.Reply.ReplyMessage != null)
{
Models.Reply _reply = new Models.Reply();
_reply.ReplyDateTime = DateTime.Now;
_reply.MessageId = messageId;
_reply.ReplyMessage = vm.Reply.ReplyMessage;
dbContext.Replies.Add(_reply);
dbContext.SaveChanges();
}
return RedirectToAction("Index", "Message");
View :
#using (Html.BeginForm("ReplyMessage", "Messages", FormMethod.Post, new { id = "form-reply-message", messageId = #ViewBag.MessageId }))
{
if (!ViewData.ModelState.IsValid)
{
#Html.ValidationSummary(true)
}
#Html.HiddenFor(model => model.Reply.MessageId);
#Html.TextAreaFor(p => p.Reply.ReplyMessage, new { #rows = 2, #class = "form-control" })
#Html.ValidationMessageFor(model => model.Reply.ReplyMessage)
<input type="submit" class="btn btn-primary btn-success" value="Reply" id="btn-reply-message">
}
You may have to bind it using [FromQuery] attribute here:
public ActionResult ReplyMessage(MessageReplyViewModel vm, [FromQuery("messageId")] int messageId)
{
........
}
This attributes reads the values after the "?" operator in the URL. Hopefully it will help!
I have a function in my controller class, it return a list of data, I want to display it in table structure in my view page.
i have tried the following code but it shows some error
"Class does not contain definition of GetEnumerator"
Controller
public ActionResult data(Message msg,IEnumerable<sample> dept)
{
dbconnection db = new dbconnection();
sample s = new sample();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt;
List<examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
dept = datatable;
}
ViewBag.tabledata = dept;
return View(dept) ;
}
Model
public class sample
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public string Location { get; set; }
public string tabledata { get; set; }
}
public class Message
{
public IEnumerable<sample> sampleList { get; set; }
public string MessageText { get; set; }
public string MessageFrom { get; set; }
}
View
#model examplemvc1.Models.sample
#foreach (var data in Model)
{
<table><tr><td>#data.FirstName</td></tr></table>
}
UPDATE
this is how my entire view looks like
#model List<examplemvc1.Models.sample>
#{
ViewBag.Title = "Registration Form";
}
<head>
<script type="text/javascript" src="../../Scripts/jquery-1.7.1.min.js"></script>
<link href="../../Style/sample.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/samplescript.js" type="text/javascript"></script>
</head>
<h2>
Registration Form </h2>
<body>
<table>
<tr>
<th>
First Name
</th>
</tr>
#foreach (var data in Model)
{
<tr><td>#data.FirstName</td></tr>
}
</table>
#using (Html.BeginForm())
{
<table id="table1">
<tr>
<td>
#Html.Label("Enter FirstName", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.FirstName, new { #class = "class1", title = "Enter FirstName", id = "NameBox", placeholder = "Enter name", onkeydown = "return TextField(event)" })
<span class="errorMessage"></span>
#if (!ViewData.ModelState.IsValid)
{
<span class="field-validation-error">
#ViewData.ModelState["FirstName"].Errors[0].ErrorMessage</span>
}
</td>
</tr>
<tr>
<td>
#Html.Label("Enter LastName", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.LastName, new { #class = "class1", placeholder = "Enter name", id = "LastNameBox", title = "Enter Lastname", onkeydown = "return TextField(event); " })
<span class="errorMessage"></span>
</td>
</tr>
<tr>
<td>
#Html.Label("Enter Address", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.Address, new { #class = "class1", id = "AddressBox", placeholder = "Enter name", title = "Enter Address" })
<span class="errorMessage"></span>
</td>
</tr>
<tr>
<td>
#Html.Label("Enter PhoneNumber", new { #class = "standard_label_style" })
</td>
<td>
#Html.TextBoxFor(a => a.PhoneNumber, new { #class = "class1", id = "PhoneBox", placeholder = "Enter name", title = "Enter Phonenumber", onkeydown = "return ValidateNumber(event);" })
<span class="errorMessage"></span>
</td>
</tr>
<tr>
<td>
#Html.Label("Enter Location", new { #class = "standard_label_style" })
</td><td>
#Html.TextBoxFor(a => a.Location, new { #class = "class1", id = "LocationBox", placeholder = "Enter name", title = "Enter Location" })
<span class="errorMessage"></span>
</td>
</tr>
</table>
<input type="button" id="btnSave" value="Register"/>
<input type="button" value="Clear"/>
<input type="button" id="Tabledata" value="Tabledata"/>
<div id="div1"></div>
#*#Html.ValidationSummary()*#
<script type="text/javascript">
function ValidateNumber(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
};
function TextField(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 56)) {
return true;
}
else if (charCode == 8 || charCode == 9) {
return true;
}
return false
};
</script>
}
</body>
Error is shown in my view code, actually I don't know how to get that values in view page. I am newbie in mvc. Please help me to solve this. Any help will be greatly appreciated.
"Update"
I have solved My problem with the help of Stackoverflow Below is my correctcode
Controller
public ActionResult data()
{
SomeViewModel model = new SomeViewModel();
dbconnection db = new dbconnection();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
sample s = new sample();
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
model.samples.Add(s);
}
return View(model);
}
Model
namespace examplemvc1.Models
{
public class sample
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string PhoneNumber { get; set; }
public string Location { get; set; }
public string tabledata { get; set; }
}
public class Message
{
public IEnumerable<sample> sampleList { get; set; }
public string MessageText { get; set; }
public string MessageFrom { get; set; }
}
public class SomeViewModel
{
public SomeViewModel()
{
samples = new List<sample>();
sample = new sample();
}
public List<sample> samples { get; set; }
public sample sample { get; set; }
}
}
view
#model examplemvc1.Models.SomeViewModel
//................
#foreach (var data in Model.samples)
{
<tr><td>#data.FirstName</td>
<td>#data.LastName</td>
<td>#data.Address</td>
<td>#data.PhoneNumber</td>
<td>#data.Location</td></tr>
}
</table>
Just look at Stephen Muecke's Answer below he has explained the context very clearly
You view is displaying both a list of sample and what appears t be a form for a new sample. Start by creating a view model to represent what you want to display/edit
public class SampleVM
{
public SampleVM
{
SampleCollection = new List<sample>
}
public List<sample> SampleCollection { get; set; }
public sample NewSample { get; set; }
}
In your controller modify the code to
public ActionResult data()
{
SampleVM model = new SampleVM();
dbconnection db = new dbconnection();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
sample s = new sample();
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
model.SampleCollection.Add(s);
}
return View(model);
}
Notes:
Remove the parameters from the GET method. Apart from the fact you
don't use them so they are pointless, even if you were to try and
pass those objects to the method, binding would fail and the
collections would be null (and if you were to construct the correct
query string to make it work, it would be so long it would almost
certainly throw an exception)
You need to initialize a new sample inside the foreach loop
(your code only initialized one object, and each loop updated its
properties to the current row, so you would end up with multiple
reference of the same object, all matching the values of the last
row in your table)
There is no need to pass the model as a ViewBag property (its
already passed to the view using return View(model);
And modify your view to
#model SampleVM
....
<table>
#foreach(var sample in Model.SampleCollection)
<tr>
<td>#sample .FirstName</td>
</tr>
}
</table>
#Html.BeginForm())
{
#Html.LabelFor(m => m.NewSample.FirstName, "Enter FirstName", new { #class = "standard_label_style" })
#Html.TextBoxFor(m => m.NewSample.FirstName, #class = "class1", placeholder = "Enter name", title = "Enter Lastname")
#Html.ValidationMessageFor(m => m.NewSample.FirstName)
}
....
<input type="submit" id="btnSave" value="Register"/>
Notes:
A label element if for associating the element with a control. Your
usage generates <label for="Enter_FirstName"> but you dont have a
control with id="Enter_FirstName". Preferable you should have
[Display(Name = "Enter FirstName")] on the property, but otherwise
use the strongly types helper
Use #Html.ValidationMessageFor() to render ModelState errors,
although in your case all you properties are strings and you don't
have any validation attributes so there will never be any errors, so
its a bit pointless
The html helpers generate an id attribute. There is rarely a need
to overwrite it. Stop polluting your markup with behavior and learn
to use Unobtrusive Javascript
Your form did not contain a submit button
Problem is your model is of Type examplemvc1.Models.sample while you have to pass object of List<examplemvc1.Models.sample> to view:
return View(datatable) ;
Your action:
List <examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
}
return View(datatable); // passing list to view
and in View set model to List<examplemvc1.Models.sample>:
#model List<examplemvc1.Models.sample>
and now iterate the way you are doing:
<table>
<thead>
<tr><th>First Name</th></tr>
</thead>
<tbody>
#foreach (var data in Model)
{
<tr><td>#data.FirstName</td></tr>
}
</tbody>
</table>
Here problem is with your model directive.
It should be
#model IEnumerable<examplemvc1.Models.sample>
instead of
#model examplemvc1.Models.sample
Note: You are making assignment few times like dept = datatable; instead you can update the code like this.
public ActionResult data(Message msg,IEnumerable<sample> dept)
{
dbconnection db = new dbconnection();
sample s = new sample();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt;
List <examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
//dept = datatable;
}
ViewBag.tabledata = datatable;
return View(datatable) ;
}
Update
In such a case you need to create viewmodel first and pass his instance there as model.
public class SomeViewModel
{
public SomeViewModel()
{
samples = new List<sample>();
sample = new sample();
}
public List<sample> samples {get; set;}
public sample sample {get; set;}
}
and in model declaration
#model namespace.SomeViewModel
and then in controller like following.
public ActionResult data(Message msg,IEnumerable<sample> dept)
{
dbconnection db = new dbconnection();
sample s = new sample();
SqlConnection con = new SqlConnection(db.GetconString());
DataTable dt;
List<examplemvc1.Models.sample> datatable = new List<sample>();
dt = db.BuildDT("select * from MVCsample");
foreach (DataRow row in dt.Rows)
{
s.FirstName = Convert.ToString(row["First Name"]);
s.LastName = Convert.ToString(row["Last Name"]);
s.Address = Convert.ToString(row["Address"]);
s.PhoneNumber = Convert.ToString(row["PhoneNumber"]);
s.Location = Convert.ToString(row["Location"]);
datatable.Add(s);
dept = datatable;
}
ViewBag.tabledata = dept;
SomeViewModel vm = new SomeViewModel();
vm.samples = datatable;
vm.sample = //somesample instance here you want to edit.
return View(vm) ;
}
and in view you will get the instance of vm iterate through vm.samples
#foreach (var data in Model.samples)
{
<tr><td>#data.FirstName</td></tr>
}
and in the rest of view do something like this:
#Html.TextBoxFor(a => a.sample.FirstName, new { #class = "class1", title =
"Enter FirstName", id = "NameBox", placeholder = "Enter name", onkeydown =
"return TextField(event)" })
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.
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?
Essentially I have a HtmlPasswordFor(m => EmployeeID), I have a button called "Go". Once I hit the Go textbox, I actually do not want the password to disappear on the or have the field password to be cleared.
How would I do this?
BEFORE
AFTER
I do not want the my employeeid to reset. I want to keep the passwords in ****'s, but I'll need the password on my next post call.
Controller
[HttpGet]
public ActionResult MainForm()
{
var model = new VTViewModel();
return View(model);
}
[HttpPost]
public ActionResult MainForm(VTViewModel model, string buttontype)
{
if (ModelState.IsValid)
{
string EmployeeID = (Convert.ToInt64(model.EmployeeBinaryID, 2)).ToString();
if (buttontype == "Go")
{
// GET Fields depending on the serial number.
model.ListFields = logic_model.getFormInfo(model.SerialNumber, EmployeeID);
if (model.ListFields[0].return_num == "0")
{
model.Go = true;
// Set Process
// Set Header Token
// Set Header Title
ViewData["HEADER"] = model.ListFields[0].HeaderName + " | " + model.ListFields[0].TubeType + " | " + model.ListFields[0].ProductLine;
}
else
{
model.DisplayMessage = helper.checkErrors(model.ListFields[0].return_num);
}
}
else if (buttontype == "Submit")
{
model.HeaderToken = model.ListFields[0].HeaderToken;
string header = model.HeaderToken;
string check = "";
string return_num = model.ListFields[0].return_num;
// If the submission worked
//SUBMIT HERE INTO DB then Clear
List<string> values_to_submit = new List<string>(); // Creates a list to store the values to submit
for (int i = 0; i < model.ListFields.Count; i++)
{
// Fills in the hidden values.
if (model.ListFields[i].isHidden)
{
if (model.ListFields[i].Token == "SNT" || model.ListFields[i].Token == "SNC")
{
model.ListFields[i].Value = model.SerialNumber;
}
else if (model.ListFields[i].Token == "USR")
{
model.ListFields[i].Value = EmployeeID;
}
else if (model.ListFields[i].Token == "TMS")
{
model.ListFields[i].Value = "0";
}
}
// If it is a check box do the right conversion.
if (model.ListFields[i].DataType == "DATA-CKBOX")
{
//string convertedValue = helper.trueFalseStringtToIntBool(model.ListFields[i].Value);
string convertedValue = helper.boolToInt(model.ListFields[i].BoolValue).ToString();
model.ListFields[i].Value = convertedValue;
}
values_to_submit.Add(model.ListFields[i].Token + model.ListFields[i].Value);
}
check = logic_model.helperSubmit(values_to_submit, header, 1);
if (check == "Submitted")
{
ModelState.Clear();
VTViewModel clear_model = new VTViewModel(); // Creates an empty model
clear_model.DisplayMessage = "Submitted\n" + model.SerialNumber + "\n" + DateTime.Now;
return View(clear_model);
}
else
{
model.DisplayMessage = check; // Sets the display message to the error.
}
}
else if (buttontype == "Clear")
{
// Clears the screen and model
ModelState.Clear();
VTViewModel clear_model = new VTViewModel(); // Creates an empty model
return View(clear_model);
}
}
return View(model);
}
View
div>
<fieldset>
<table id="main_table">
<tr>
<td>#Html.LabelFor(m => m.SerialNumber)</td>
<td>#Html.LabelFor(m => m.EmployeeBinaryID)</td>
</tr>
<tr>
<td>#Html.TextBoxFor(m => m.SerialNumber)</td>
<td>#Html.PasswordFor(m => m.EmployeeBinaryID, new { autocomplete = "off" }) </td>
</tr>
<tr><td><input type="submit" value="Go" name="buttontype" class="submit_button" id="btn"/><br /><br /></td></tr>
</table>
</fieldset>
<br />
Thanks
Html.PasswordFor will never render the value, probably for security reasons. You can work around this, but you have to use Html.EditorFor instead, decorate the EmployeeID property with [DataType(DataType.Password)] and add the following editor template at ~/Views/Shared/EditorTemplates/Password.cshtml
#Html.Password("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line password" })
You could also use [UIHint] and create a template for that particular property only.