I have a table in which each row has a jQuery datepicker in the last cell. Along with a submit button labeled 'Update'. The last cell also contains the Issue.ID in a hidden textbox. I am trying to retrieve these values in my controller but I get a System.ArgumentOutOfRangeException.
Here is part of my view:
#foreach (Issue issue in Model.IssueSet.IssueList)
{
<tr class="altsec" id="#issue.RowID">
<td>#issue.Zone.ToString()</td>
<td>#issue.Station.ToString()</td>
<td>#issue.WhenOpened.Date.ToShortDateString()</td>
<td>#issue.What.ToString()</td>
<td>#issue.Why.ToString()</td>
<td>#issue.How.ToString()</td>
<td>#issue.Who.ToString()</td>
<td>
#using (Html.BeginForm()) {
<fieldset>
<input type="text" style="width: 100px; display: none" value="#issue.ID" name="stringID"/>
<input class="datepicker" type='text' style="width: 100px" id="#issue.DateID" />
<input class="updateButtons" type="submit" value="Update" /></fieldset>
}</td>
</tr>
}
My controller for POST is as follows:
[HttpPost]
public ActionResult Index(string stringID)
{
var ID = Request.Form[0].ToString();
var date = Convert.ToDateTime(Request.Form[1]);
string strSQL = "UPDATE bp_open_issues SET WhenFixed = '" + date + "' WHERE ID = '" + ID + "' ";
SqlConnection con =
new SqlConnection("Data Source=10.67.XX.XXX;Initial Catalog=XXX111; User Id=XXXXXX; Password=XXXXXX;");
SqlCommand cmd = new SqlCommand(strSQL, con);
con.Open();
cmd.ExecuteNonQuery();
TempData["msg"] = "<script>alert('Change succesfully');</script>";
return Redirect("/");
}
Related
I am trying to get to save a form with many rows at once.If it is just one single row, I am able to insert into DB successfully, but having challenge reading a form array and storing it to the Database.
The View:
<tbody>
#{int c = 0;
foreach (var item in Model)
{
c++;
<tr>
<td>#c</td>
<td>#item.FltNo<input type="hidden" name="FltNo[#c]" value="#item.FltNo"/></td>
<td>#item.FleetModelName<input type="hidden" name="Fltmodel[#c]" value="#item.FleetModelName"/></td>
<td>#item.EngineName<input type="hidden" name="Engine[#c]" value="#item.EngineName"/></td>
<td>#item.LocationName<input type="hidden" name="Location[#c]" value="#item.LocationName"/></td>
<td>#item.ServiceType<input type="hidden" name="ServiceType[#c]" value="#item.ServiceType"/></td>
<td>#item.ServiceSequence<input type="hidden" name="NextSvr[#c]" value="#item.ServiceSequence"/></td>
</tr>
}
}
The Controller
public IActionResult Create(string ButtonClicked, Mrptran trans)
{
if (ButtonClicked == "GenerateBtn")
{
var mrpData = new Mrptran
{
FltNo = trans.FltNo,
Fltmodel = trans.Fltmodel,
Engine = trans.Engine,
Location = trans.Location,
ServiceType = trans.ServiceType,
NextSvr = trans.NextSvr,
CreatedBy = User.Identity.Name,
CreatedAt = DateTime.UtcNow,
};
_context.Mrptrans.Add(mrpData);
_context.SaveChanges();
}
}
Question: How do I read the form array to the Database once. I am using Entity-Framework.Any Suggestion will be appreciated.
After Serveral Troubleshooting and looking at Stalkoverflow again and again, I was able to figure it out and so, decide to post it ,perhaps to help someone, someday.
1. I added an hidden field in the View to keep track of the Total Row.
2. I modified the Save Action method to loop over the Total Row, while saving it to DB. This works, but if there is a better way, it will be appreciated.
The Updated View
<input type="hidden" name="TotalRecord" value="#Model.Count()" />
foreach (var item in Model)
{
c++;
<tr>
<td>#c</td>
<td>#item.FltNo<input type="hidden" name="FltNo[#c]" value="#item.FltNo" /></td>
<td>#item.FleetModelName<input type="hidden" name="Fltmodel[#c]" value="#item.FleetModelName" /></td>
<td>#item.EngineName<input type="hidden" name="Engine[#c]" value="#item.EngineName" /></td>
<td>#item.LocationName<input type="hidden" name="Location[#c]" value="#item.LocationName" /></td>
<td>#item.ServiceType<input type="hidden" name="ServiceType[#c]" value="#item.ServiceType" /></td>
<td>#item.ServiceSequence<input type="hidden" name="NextSvr[#c]" value="#item.ServiceSequence" /></td>
</tr>
}
}
</tbody>
The Controller
public IActionResult Create(Mrptran trans, int? TotalRecord)
{
for(int i = 1; i <=TotalRecord; i++)
{
var mrpData = new Mrptran
{
FltNo = Request.Form["FltNo["+i+"]"],
CostUnit = Request.Form["CostUnit[" + i+"]"],
CreatedBy = User.Identity.Name,
CreatedAt = DateTime.UtcNow,
Engine = Request.Form["Engine[" + i+"]"],
Fltmodel = Request.Form["Fltmodel[" + i + "]"],
Location = Request.Form["Location[" + i + "]"],
PartNo = Request.Form["PartNo[" + i + "]"],
Mtypes = "S",
NextSvr = Request.Form["NextSvr[" + i + "]"],
};
_context.Mrptrans.Add(mrpData);
_context.SaveChanges();
}
}
I'm new in learning asp.net MVC. I am writing because I am stubborn to a problem. Indeed, I have an application that should allow me to create an XML file that will be added to a database. At this point, I created my Model, and my view that allows me to create my XML tags.
I saw on this site that could add lines in my table via Javascript. What I have done just as you can see in the code.
I can not recover what is the value of each line that I can insert. Passing my view a list I created myself. I can recover both inputs I inserted in my controller.
My question is, there's another way to create a dynamic lines via javascript, then all the entries that the user has entered the recover and fill in my list? Then I know myself how I can play with my list. But I just want to recover all the different lines that my user has inserted. I am new in ASP.NET MVC. Any help , please
This is my code.
Model
public class XMLFile
{
public string TypeDoc { get; set; }
public string Type { get; set; }
public string Contenu { get; set; }
public string DocName { get; set; }
}
This is my controller :
public class XMLFileController : Controller
{
List<XMLFile> file = new List<XMLFile>();
[HttpGet]
public ActionResult Save()
{
file.AddRange( new XMLFile[] {
new XMLFile (){Type = "Titre", Contenu = "Chef de Service"},
new XMLFile (){Type = "Item", Contenu="Docteur Joel"}
});
return View(file);
}
[HttpPost]
public ActionResult Save(List<XMLFile> formCollection)
{
try
{
if (formCollection == null)
{
return Content("la liste est nulle");
}
else
{
return RedirectToAction("Create", "Layout");
}
}
catch
{
return View();
}
}
}
My view with a script for adding a new Row :
#using (Html.BeginForm("Save", "XMLFile", FormMethod.Post,new { #class = "form-horizontal", #role = "form", #id = "FormCreateXML" }))
{
<table class="table table-bordered" id="XMLFileTable">
<thead>
<tr>
<th>Type</th>
<th>Contenu</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#for (int i = 0; i<Model.Count; i++)
{
<tr>
<td>#Html.TextBoxFor(model=>model[i].Type, new {#class="form-control help-inline", #placeholder="type" })</td>
<td> #Html.TextBoxFor(model=>model[i].Contenu, new {#class="form-control help-inline", #placeholder="contenu" })</td>
<td> <input type="button" class="BtnPlus" value="+" /> </td>
<td> <input type="button" class="BtnMinus" value="-" /> </td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td> <button type="submit" class="btn btn-success" >Save</button> </td>
</tr>
</tfoot>
</table>
}
</body>
<script type="text/javascript">
$(document).ready(function () {
function addRow() {
var html = '<tr>' +
'<td><input type="text" class="form-control" placeholder="type"></td>' +
'<td> <input type="text" class="form-control" placeholder="contenu"></td>' +
'<td> <input type="button" class="BtnPlus" value="+" /> </td>' +
'<td> <input type="button" class="BtnMinus" value="-" /></td>' +
'</tr>'
$(html).appendTo($("#XMLFileTable"))
};
function deleteRow() {
var par = $(this).parent().parent();
par.remove();
};
$("#XMLFileTable").on("click", ".BtnPlus", addRow);
$("#XMLFileTable").on("click", ".BtnMinus", deleteRow);
});
</script>
I need to pass a form element into an MVC4 view using ViewBag. The Viewbag is a list of 1 or more records for each user. The issue is nothing is being passed.
controller
// grab all records for user id 26000.
var qry = db.users.Where(m => m.user_id == "26000").ToList();
foreach (var myBag in qry)
{
// place all the items in the Viewbag.
ViewBag.myItems = "<input type='text' name=#ViewBag.myBag value=#ViewBag.myBag>";
}
view
#using (Html.BeginForm("Index", "Home"))
{
foreach (var item in ViewBag.myBag)
{
<label for="#item">#item</label>
<input type="checkbox" name="#item" value="#item"/>
}
<input id='btnSubmit' type="submit" value='submit' />
}
Controller (the query should really be in your Model).
ViewBag.myItems = db.users.Where(m => m.user_id == "26000").ToList();
View
#using (Html.BeginForm("Index", "Home"))
{
foreach (var item in ViewBag.myItems)
{
<input type="text" name="#item.user_id" value="#item.user_name">
}
<input id='btnSubmit' type="submit" value='submit' />
}
I would like to return empty model on httpget in a mvc4 razor view. I'll be fetching the model on httppost once the user will select the value from a dropdownlist.
This is what I have:
[HttpGet]
public ActionResult AddNewAgent()
{
var modelAgentt = _fe.Agents.Take(1);
SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new {COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME}), "COUNTER", "FullName", null);
ViewBag.Agent= sl;
return View(agg);
}
Then at HttpPost I have:
[HttpPost]
public ActionResult AddNewAgent(int? LamcomAgents)
{
var modelAgent = _fe.Agents.Take(10);
SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new { COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME }), "COUNTER", "FullName", null);
ViewBag.Agent= sl;
if (LamcomAgents != null && LamcomAgents != 0)
{
return View(modelAgent);
}
return View(modelAgent);
}
The proper linq query is not still included in the httppost action but I'll do that later, i just want to know how I can pass nullable model for the httpget at the first run without getting error in the view.
This is what I have in the view:
#model IEnumerable<Company.Agents>
#{
ViewBag.Title = "AddNewAgent";
}
<h2>Add New Agent</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<p>Agents in System #Html.DropDownList("Agent", String.Empty) <input type="submit" name="Get Agent" value="Get Agent" title="Get Agent" id="btnGetAgent" /></p>
<legend>Agents</legend>
<table>
<tr>
<th>#Html.DisplayNameFor(model => model.A_FirstName)</th>
<th></th>
</tr>
<tr>
</tr>
#foreach(var item in Model)
{
<tr><td>
#Html.DisplayFor(modelItem => item.A_FirstName)
</td></tr>
}
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Thanks in advance, Laziale
Assuming that modelAgentt is of type IEnumerable<Company.Agents>
I think you need to pass modelAgentt to view instead of agg
So change your code from in Get Method
return View(agg);
to
return View(modelAgentt);
I have a webpage with 2 list box (list1, list2), I can shift items from one listbox to the other and back. When I click on the submit button, I want to return all the items value in list2 to the httppost method.
I have 3 problems:
How to definite the property for the selected list?
How to have a initial empty list (for list2)? list1 has populated items?
How to return all of list2 items to model, when submit button is clicked ?
Model:
public class TestModel
{
public List<SelectListItem> OptionList { get; set; }
public List<SelectListItem> SelectedOptionList { get; set; }
public string[] SelectedOptions { get; set; }
}
Controller:
private TestModel testModel = new TestModel();
public ActionResult TestPage()
{
ViewBag.Message = "Test Page";
testModel.OptionList = new List<SelectListItem>();
for (int i = 1; i <= 100; i++)
{
SelectListItem item = new SelectListItem();
item.Text = "Option " + i.ToString();
item.Value = item.Text;
testModel.OptionList.Add(item);
}
return View("TestView", testModel);
}
[HttpPost]
public ActionResult TestPage(TestModel formModel)
{
testModel.SelectedOptionList = formModel.SelectedOptionList;
testModel.SelectedOptions = formModel.SelectedOptions;
//do something
return RedirectToAction("TestPage");
}
View:
#model EngineeringDataAnalysisGui.Models.TestModel
#{
ViewBag.Title = #ViewBag.Message;
}
#section Subtitle
{
#ViewBag.Message
}
<table width="100%">
#using (Html.BeginForm("TestPage", "RetrieveData", FormMethod.Post))
{
<tr>
<td>Event List:</td>
<td>#Html.ListBox("lstEventSelection", Model.OptionList, new { id = "list1", Multiple = "multiple", Size = 15, style = "width: 100%;" })</td>
</tr>
<tr>
<td></td>
<td>
<table style="text-align:center; width: 100%">
<tr>
<td id="buttonCol">
<input type="button" id="btnAddAllEvent" title="Add All Events" onclick="moveAllOptions('list1','list2', true)" />
<input type="button" id="btnAddEvent" title="Add Selected Events" onclick="moveSelectedOptions('list1','list2', true)" />
</td>
<td id="buttonCol">
<input type="button" id="btnRemoveEvent" title="Remove Selected Events" onclick="moveSelectedOptions('list2','list1', true)" />
<input type="button" id="btnRemoveAllEvent" title="Remove All Events" onclick="moveAllOptions('list2','list1', true)" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>Selected Event List:</td>
#*Not sure how to add the listbox*#
<td>#*Wrong*##Html.ListBoxFor(x => x.SelectedOptions, Model.SelectedOptionList, new { id = "list2", Multiple = "multiple", Size = 15, style = "width: 100%;" })</td>
</tr>
<tr>
<td><input type="submit" value="submit" /></td>
</tr>
}
</table>
1) How to definite the property for the selected list?
#Html.ListBoxFor(x => x.SelectedOptions, new MultiSelectList(Model.SelectedOptionList), new { id = "list2", Multiple = "multiple", Size = 15, style = "width: 100%;" })
2) How to have a initial empty list (for list2)? list1 has populated items.
In controller set an empty list testModel.SelectedOptionList = new List<SelectListItem>();
3) How to return all of list2 items to model when submit button is clicked
Probably you need to set all the items in list2 as selected (using jquery) before submitting. All the selected items in list2 items will bind to TestModel.SelectedOptions on submit.
Please look around, there are a lot of answers already in SO related to Html.ListBoxFor. for e.g Challenges with selecting values in ListBoxFor