How to get MVC button to populate and display a table after being clicked - asp.net-mvc

I've looked for 4 or 5 hours now on how to get this to work but I simply cannot figure it out. I'm suppose to get a form that has both a submit and delete button. The submit should submit the data in the form to a table that gets populated and created at the same time while the delete button would delete the most recent addition. It doesn't seem to matter what I've tried to do it just doesn't work. Whenever I click on my save button it just reloads the page with empty form fields and no table with the data.
My Controller code
public class PersonController : Controller
{
private static List<Person> Persons = new List<Person>();
public ActionResult Index()
{
return View();
}
public ActionResult Start()
{
return View("PersonData");
}
public ActionResult AddPerson(string firstName, string lastName, string birthDate)
{
Person p = new Person();
p.firstName = firstName;
p.lastName = lastName;
p.birthDate = birthDate;
if (Persons.Count > 0)
{
Persons.Add(p);
}
return View("PersonData");
}
public ViewResult DeletePerson()
{
if(Persons.Count > 0)
{
Persons.RemoveAt(0);
}
return View("PersonData");
}
}
My View code
#model IEnumerable<UsingViewsandModels.Models.Person>
....
#using (Html.BeginForm("AddPerson", "PersonController"))
{
}
<form>
<label name="firstName">First Name: </label>
<input type="text" name="firstName" />
<br />
<label name="lastName">Last Name: </label>
<input type="text" name="lastName" />
<br />
<label name="birthDate">Birth Date: </label>
<input type="text" name="birthDate" />
<br />
<button type="submit" value="Submit" name="AddPerson" onclick="AddPerson()">Save</button>
<button type="submit" value="Delete" name="DeletePerson" onclick="DeletePerson()">Delete</button>
</form>
#if (Model != null && Model.Count() > 0)
{
<table>
<tr><th>FirstName</th><th>LastName</th><th>BirthDate</th></tr>
#foreach (UsingViewsandModels.Models.Person p in Model)
{
<tr>
<td>p.firstName)</td>
<td>p.lastName)</td>
<td>p.birthDate)</td>
</tr>
}
</table>
}
Any help would be greatly appreciated. I'm fairly certain I'm just being an idiot and it's something very simple.

You have this code:
return View("PersonData");
That means: return the view named "PersonData".
You are not sending no data to the view. Use the overload and send the model to your view like this:
return View("PersonData", Persons);
Now your view has access to all the data in Persons and it will work.

Related

I have a question how to add input fields values with same name into the database using entity framework? Below is my code,

This is my HomeWithIndentityController
namespace MVC.CRUDDynamicFormTest.Controllers
{
public class HomeWithIndentityController : Controller
{
// GET: HomeWithIndentity
public ActionResult WithIndex()
{
return View();
}
public ActionResult GetData()
{
using (DynamicCRUDDatabase2Entities db = new DynamicCRUDDatabase2Entities())
{
List<DynamicCRUDTable2> dynamicCRUDTable2s = db.DynamicCRUDTable2.ToList<DynamicCRUDTable2>();
return Json(new { data = dynamicCRUDTable2s }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult Add(int id = 0)
{
return View(new DynamicCRUDTable2());
}
[HttpPost]
public ActionResult Add(DynamicCRUDTable2 obj)
{
using (DynamicCRUDDatabase2Entities db = new DynamicCRUDDatabase2Entities())
{
db.DynamicCRUDTable2.Add(obj);
db.SaveChanges();
return Json(new { succces = true, message = "saved Successfully" }, JsonRequestBehavior.AllowGet);
//return RedirectToAction("Index", "Home");
}
}
}
}
this is my entity model class
public partial class DynamicCRUDTable2
{
public int Id { get; set; }
public string FirstName { get; set; }
}
This my View
<form action="~/HomeWithIndentity/Add" method="POST" onsubmit="return Submitform(this)">
<input data-val="true" id="Id" name="Id" type="hidden" />
<label>First Name</label>
<input type="text" name="FirstName[]" class="form-control" />
<input type="text" name="FirstName[]" class="form-control" />
<br />
<br />
<div>
<input type="submit" value="Submit" class="btn btn-success" />
<input type="reset" value="Reset" class="btn btn-danger" />
<a class="btn btn-danger" href="~/Home/Index">Cancel</a>
</div>
</form>
In the above view i want to add the firstname input field values to the Database dynamicallly.but it does not working can you let me know why?What errors i have done.
does anyone know how to do that?

mvc passing data from view to controller

My Controller
public class OgrenciController : Controller
{
[HttpPost]
public ActionResult home(int perId)
{
if(perId=="anything")
{
//something
}
return View();
}
}
This is my view
#foreach (var item in Model)
{
siraNo++;
<form method="post">
<input type="radio" name="perId" value="#item.specialId">
<input type="submit" value="send" />
</form>
}
but in the POST method, perId not take anythings
use something like this.
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<input type="radio" name="perId" value="#item.specialId"><br /><br />
}
<input type="submit" ur value="send" />
}

check the checkbox based on model in mvc?

I have a edit form which should have checkbox.
My Model for the page is
public class MyModel{
public string Name {get;set;}
public List<AdType> AdTypeList { get; set; }
}
Enum AdType{
[Display(Name = "None")]
None,
[Display(Name = "Additional")]
Additional_Photo,
}
So i have to check the check box with respect to the data coming from the database.
And also update should happen if i make changes and submit.
To work that way what changes i need to make in my html helper for the checkbox?
foreach (AdType role in Enum.GetValues(typeof(AdType)))
{
<label>
<input name="Roles" type="checkbox" value="#role" checked="#(Model != null)" />
#{var x = EHelper.GetDisplayValue<AdType>(role);}
#x
</label>
}
I am new to mvc, please parden if i m doing something stupid.
you can put if else condition in model to create condition based html control
foreach (AdType role in Enum.GetValues(typeof(AdType)))
{
<label>
#if(Model != null)
{
<input name="Roles" type="checkbox" value="#role" checked="checked" />
}
else
{
<input name="Roles" type="checkbox" value="#role" />
}
#{var x = EHelper.GetDisplayValue<AdType>(role);}
#x
</label>
}
#foreach (AdType role in Enum.GetValues(typeof(AdType)))
{
<label class="col-sm-12">
<input name="AdTypeList" type="checkbox" value="#role" checked="#(Model != null && Model.AdTypeList!= null && Model.AdTypeList.Any(i => i.HasFlag(role)))" />
#{var text = EHelper.GetDisplayValue<AdType>(role);}
#text
</label>
}

Pass Object from view to controller using mvc4

View
#if (weekMaster != null)
{
using (Html.BeginForm("UpdatePlan", "generalPlan", FormMethod.Post, new { }))
{
<table class="table-bordered">
<tr>
#foreach (TermMaster obj in weekMaster.ToList())
{
<td align="center">
<span> #obj.termStartDate.ToString("dd MMM") - #obj.termEndDate.ToString("dd MMM")</span>
<br />
<input type="hidden" name="ObjHid" value="#obj" />
<input type="hidden" name="startDate" value="#obj.termStartDate" />
<input type="hidden" name="endDate" value="#obj.termEndDate" />
<input type="text" style="width:80%" name="weekSession" />
</td>
}
<td>
<input type="submit" value="Update" class="btn-primary" />
</td>
</tr>
</table>
} }
Controller
[HttpPost]
public ActionResult UpdatePlan(List<DateTime> startDate, List<DateTime> endDate, List<int> weekSession, List<TermMaster> ObjHid)
{
return View();
}
I am trying pass Class Object from View to Controller above TermMaster class Object pass using input method <input type="hidden" name="ObjHid" value="#obj" /> but showing NULL value if pass single value like startDate and endDate then it work fine.
What is wrong in my code? how to pass class object List in Post Method?
Please refer Image
You can not bind objects to controller from your input. You can serialize object to json. In the controller you can take your inputs value as string and deserialize it.
You have to do it by below approach.
Create a model instead of multiple parameters, and use index in cshtml.
public class model
{
public List<DateTime> startDate { get; set; }
public List<DateTime> endDate { get; set; }
public List<int> weekSession { get; set; }
public List<TermMaster> ObjHid { get; set; }
}
CSHTML
#{ int i = 0; }
#foreach (TermMaster obj in weekMaster.ToList())
{
<td align="center">
<span> #obj.termStartDate.ToString("dd MMM") - #obj.termEndDate.ToString("dd MMM")</span>
<br />
<input type="hidden" name="ObjHid[#i].termStartDate" value="#obj.termStartDate.ToString("dd MMM")" />
<input type="hidden" name="ObjHid[#i].termStartDate" value="#obj.termStartDate.ToString("dd MMM")" />
<input type="hidden" name="startDate[#i]" value="#obj.termStartDate" />
<input type="hidden" name="endDate[#i]" value="#obj.termEndDate" />
<input type="text" style="width:80%" name="weekSession[#i]" />
</td>
i++
}

ViewData not being posted back to Controller

I have two pages, one that edits user information, and one that edits information in a pictures table. I recently stopped using strongly typed viewmodels due to the varying types of data required on each page.
The page that edits the user information works fine, but the page that edits picture information does not post back any of the edits that are made in the input fields; except for the ID, which is correct, all the other values come back as null. They both seem to be structured exactly the same way -- I can't figure out what's the difference. As far as I can tell the code for both pages are the same, but I'm not getting data back on the second one.
User Controller and View which works
Controller
public ActionResult Preferences()
{
int userid = getUserID(User.Identity.Name);
// Info for user preferences
var accountInfo = db.users.Single(l => l.ID == userid);
ViewData["accountInfo"] = accountInfo;
AccountController usr = new AccountController(); // Info for user menu
ViewData["userInfo"] = usr.getUserInfo(User.Identity.Name);
return View();
}
[HttpPost]
public ActionResult Preferences(user accountInfo, string oldPW)
{
// Do stuff to save user info
return RedirectToAction(actionname, routeValues);
}
View
#using (Html.BeginForm("Preferences", null, FormMethod.Post,
new { id = "prefsform" }))
{
AutoShowApp_MVC.user item = new AutoShowApp_MVC.user();
item = ViewBag.accountInfo;
<input id="lastname" name="lastname" type="text" value="#item.lastname"/>
<input id="address1" name="address1" type="text" value="#item.address1"/>
<input id="city" name="city" type="text" value="#item.city"/>
<input id="state" name="state" type="text" value="#item.state"/>
<input type="submit" value="Submit Changes" />
}
Picture Controller and View which DON'T work
Controller:
public ActionResult Edit(long id)
{
var picInfo = db.lmit_pics.Single(l => l.ID == id);
ViewData["picInfo"] = picInfo; // get Picture Info
// Get User Info for menu
AccountController usr = new AccountController();
ViewData["userInfo"] = usr.getUserInfo(User.Identity.Name);
return View();
}
[HttpPost]
public ActionResult Edit(lmit_pics picInfo)
{
// Do stuff to save picInfo
return RedirectToAction("Index");
}
View:
#using (Html.BeginForm("Edit", null, FormMethod.Post, new { id = "editform" }))
{
AutoShowApp_MVC.lmit_pics item = new AutoShowApp_MVC.lmit_pics();
item = ViewBag.picInfo;
<input type="text" id="model" value="#item.model" />
<input type="text" id="description" value="#item.description" />
<input type="submit" value="Save" />
}
You do not have the name attribute specified on the inputs on your picture editing form.
<input type="text" id="model" value="#item.model" />
Should Be
<input type="text" id="model" name="model" value="#item.model" />
The form collection works from the name attribute, not the Id attribute which is why you are not getting any data back (you are, it is just not properly attributed).
However, I agree with Wahid above, using strongly typed view models, editorFor helpers, etc not only help to prevent issues such as the above, but really go a long way in making a more secure, easier to maintain site.

Resources