HTML Helpers not working after sending blank value in textbox - asp.net-mvc

I am banging my head for the last 3 hours and I don't know what is wrong.
My question is, Why HTML helpers are not working when I submit a blank value in ProjectCode. Below are my View and Controller?
View:
#using Models;
#model LoginViewModel
#{
ViewBag.Title = "Login";
Layout = "~/Views/_MainTheme.cshtml";
}
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
#Html.TextBoxFor(x => x.ProjectCode)
<input type="submit" name="Search" value="Search" />
<br />
#Html.ActionLink("Create", "Details", "NewSurvey")
<br />
<div style="display:#(Model.SurveyList.Surveys.Count > 0 ? "block" : "none");">
<div>#Model.SurveyListTableHeader</div>
<table border="1">
<thead>
<tr>
<td>Project Code</td>
<td>Project Name</td>
</thead>
#foreach (var survey in Model.SurveyList.Surveys)
{
<tr>
<td>#survey.Value.ProjectCode</td>
<td>#survey.Value.ProjectName</td>
}
</table>
</div>
}
Controller:
public ActionResult Login()
{
Session["CurrentPage"] = ePages.Login;
LoginViewModel login = new LoginViewModel();
login.SurveyList = BusinessOperations.GetExistingUserSurveys("mp12672", ref ScreenMessages._Message, ref ScreenMessages._MessageStateID);
login.SurveyListTableHeader = "Recently Accessed Surveys";
return View("Login", login);
}
public ActionResult Search(LoginViewModel login)
{
Session["CurrentPage"] = ePages.Login;
login.SurveyList = BusinessOperations.GetProjectSurveys(login.ProjectCode, ref ScreenMessages._Message, ref ScreenMessages._MessageStateID);
login.SurveyListTableHeader = "Surveys matching your search";
return View("Login", login);
}
public ActionResult Resume(string SurveyKey)
{
Session["SurveyKey"] = SurveyKey;
return RedirectToAction("Introduction", "OMS");
}
}
The exception I get is:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
on the below line
#Html.ActionLink("Create", "Details", "NewSurvey")

Related

How to Solve this error when I m uploading image in MVC?

I m working with MVC with SQL server management studio?
Error: No parameterless constructor defined for this object
I won't know what is the error?
I change in 3 places
1.Index.cshtml
2.create.cshtml
3.CrudManuallyController.cs
public string Image { get; set; } varchar(50)
CrudManually Controller:
public class CrudManuallyController : Controller
{
public ActionResult Create()
{
return View();
}
// POST: CrudManually/Create
[HttpPost]
public ActionResult Create(manage manages,HttpPostedFileBase image)
{
try
{
var folderPath = Server.MapPath("~/Images/");
image.SaveAs(Path.Combine("~/Images/", image.FileName));
manages.Image = Path.Combine("~/Images/", image.FileName);
// TODO: Add insert logic here
db.manages.Add(manages);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(manages);
}
}
}
create.cshtml
<h2>Create</h2>
#using (Html.BeginForm("Create", "CrudManually", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
<input id="Image" title="Image Uploading" type="file" name="image" />
</div>
}
Index.cshtml
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Image)
</th>
</tr>
<tr>
#foreach (var item in Model)
{
<td>
<img src="#Url.Content(item.Image)" alt="Image not display" width="20%" height="20%" />
</td>
}
</tr>
</table>
Image:
enter image description here
How to solve this error?
I won't know what is the error?
any code adds in my program and runs my image uploading successfully What Can I DO?
Image1:
enter image description here
Controller Code
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(manages manages, HttpPostedFileBase image)
{
try
{
if (image != null)
{
//using System.IO;
var folderPath = Server.MapPath("~/Images/");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
//Path.Combine for concate folder path and image name together
var imagePathName = Path.Combine(folderPath, image.FileName);
image.SaveAs(imagePathName);
manages.Image = image.FileName;
//TODO: Add insert logic here
//db.manages.Add(manages);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View(manages);
}
}
create.cshtml code
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
Image
</div>
<div class="editor-field">
<input id="Image" title="Image Uploading" type="file" name="image" />
</div>
<input type="submit" value="button" />
}
Index.cshtml
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Image)
</th>
</tr>
<tr>
#foreach (var item in Model)
{
<td>
<img src="#Url.Content('~/Images/' + item.Image)" alt="Image not display" width="20%" height="20%" />
</td>
}
</tr>
</table>
CrudManually Controller
//replace HttpPostedFile with HttpPostedFileBase object
//please add server.Mappath function into code for exact foler structure to save file
public class CrudManuallyController : Controller
{
public ActionResult Create()
{
return View();
}
// POST: CrudManually/Create
[HttpPost]
public ActionResult Create(manage manages,HttpPostedFileBase image)
{
try
{
var folderPath = Server.MapPath("~/Images/");
image.SaveAs(Path.Combine(folderPath, image.FileName));
manages.Image= Path.Combine(folderPath, image.FileName);
// TODO: Add insert logic here
db.manages.Add(manages);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(manages);
}
}
}
create.cshtml
//encytype is wrong please replace it with enctype
//input file name="file" so it will not set on controller side as its name on controller side is 'image', so you need to repalce name='file' with name='image'
<h2>Create</h2>
#using (Html.BeginForm("Create", "CrudManually", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
<input id="Image" title="Image Uploading" type="file" name="image" />
</div>
}
Index.cshtml
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Image)
</th>
</tr>
<tr>
#foreach (var item in Model)
{
<td>
<img src="#Url.Content('~/Images/' + item.Image)" alt="Image not display" width="20%" height="20%" />
</td>
}
</tr>
</table>
Explaination :
ASP.NET C# MVC provides the facility of HttpPostedFileBase class is an abstract class that contains the same members as the HttpPostedFile class. so we can use this abstract class while work with uploading file onto server.
Step 1: For that, we need to use input type of file with name attribute.
Step 2: Form must be POST with enctype = "multipart/form-data"
Step 3: On the controller side we need to get HttpPostedFileBase object value with the same name which we already gave to input file type
public ActionResult Create(manage manages,HttpPostedFileBase image)
Step 4: After follow all the steps on Form post you will get the value of file in the image object of type HttpPostedFileBase and then you need to check the nullable condition and simply code foe save the file.
var virtualPath = StaticValues.AdvertisementImagePath;
var physicalPath = Server.MapPath(virtualPath);
Utilities.SaveFile(fileObject, virtualPath, physicalPath, "FILE PATH");

Issue with mvc, partial view dispaying

I have a question about partial view. I want to display in header Login form which i created. In HomeController I have 2 actions: one is Login and other is Login with httppost method.
In partial view (_Layout.cshtml) I have a code - only send footer div:
<td style="text-align:center">
<h3>Bookstore</h3>
#Html.Partial("_LoginPartial")
</td>
In Login view I have:
#using(Html.BeginForm("Login", "Home", FormMethod.Post)){
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<table>
<tr>
<td>#Html.LabelFor(a=>a.Username)</td>
<td>#Html.TextBoxFor(a=>a.Username)</td>
<td>#Html.ValidationMessageFor(a=>a.Username)</td>
</tr>
<tr>
<td>#Html.LabelFor(a=>a.Password)</td>
<td>#Html.PasswordFor(a=>a.Password)</td>
<td>#Html.ValidationMessageFor(a=>a.Password)</td>
</tr>
<tr>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>}
Controller
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Users u)
{
if (ModelState.IsValid) {
using (DatabaseLoginEntities dl = new DatabaseLoginEntities()) {
var v = dl.Users.Where(a => a.Username.Equals(u.Username) && a.Password.Equals(u.Password)).FirstOrDefault();
if (v != null) {
Session["LogedUserId"] = v.UserAccountID.ToString();
Session["LogedUserFullName"] = v.FullName.ToString();
return RedirectToAction("AfterLogin");
}
}
}
return PartialView("_LoginPartial", u);
}
When press Login button, mvc switches me to separate page in which Login form is shown. I don't want that to happen. It must stay in header. Functionality is ok but I have issue how to show that only in header. Has anyone have idea where I'm wrong?
you must use ajax
#using (Ajax.BeginForm("Login", "Home",
new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace
,
UpdateTargetId = "div_id"
}
)){
<table>
<tr>
<td>#Html.LabelFor(a=>a.Username)</td>
<td>#Html.TextBoxFor(a=>a.Username)</td>
<td>#Html.ValidationMessageFor(a=>a.Username)</td>
</tr>
<tr>
<td>#Html.LabelFor(a=>a.Password)</td>
<td>#Html.PasswordFor(a=>a.Password)</td>
<td>#Html.ValidationMessageFor(a=>a.Password)</td>
</tr>
<tr>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>
}

fiil a list with values of a table

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>

mvc4 razor return empty model on httpget

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);

error to get value from controller

i try to create new room, but roomTypeID always return 1, whats wrong with my code?
i can make a new room type, but i cant insert room facility in my database, because RoomType ID always return 1
this my code..
my controller
public ActionResult NewRoom()
{
ViewBag.hotel = _hotelService.GetByID(_HotelID).HotelName;
List<ShowEditRoomViewModel> showEditRoomViewModel = _roomTypeService.showNewRooms();
return View(showEditRoomViewModel.FirstOrDefault());
}
[HttpPost]
public ActionResult NewRoom(FormCollection typeRoom)
{
_roomTypeService.NewRoom(_HotelID, typeRoom["RoomTypeName"], typeRoom["RoomTypeDescription"]);
List<string> IDs = typeRoom["FacilityIDs"].Split(',').ToList();
List<int> FacilityIDs = new List<int>();
foreach (string ID in IDs)
{
FacilityIDs.Add(Convert.ToInt32(ID));
}
_roomTypeService.UpdateFacilityInRooms(FacilityIDs, Convert.ToInt32(typeRoom["RoomTypeID"]));
return NewRoom();
}
my service
public void UpdateFacilityInRooms(List<int> FacilityIDs, int RoomTypeID)
{
List<HotelRoomFacility> hotelRoomFacilities = _HotelRoomFacilityRopository.AsQueryable().Where(f => f.RoomTypeID == RoomTypeID).ToList();
foreach (int newRoomFacility in FacilityIDs)
{
if (hotelRoomFacilities.Where(h => h.RoomFacilityID == newRoomFacility).Count() == 0)
{
HotelRoomFacility facility = new HotelRoomFacility
{
RoomFacilityID = newRoomFacility,
RoomTypeID = RoomTypeID
};
_HotelRoomFacilityRopository.Add(facility);
}
}
_HotelRoomFacilityRopository.CommitChanges();
}
my view model
public class ShowEditRoomViewModel
{
public int RoomTypeID { get; set; }
public string RoomTypeName { get; set; }
public string RoomTypeDescription { get; set; }
public List<FaciliyInRoom> facilityinRoom { get; set; }
}
my view
#model XNet.Repository.Model.ShowEditRoomViewModel
#{
ViewBag.Title = "NewRoom";
}
<h2>New Room</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Isikan Data</legend>
<div>
#Html.Label("Hotel Name")
</div>
<div>
#ViewBag.hotel
</div>
<br />
<div>
#Html.HiddenFor(model => model.RoomTypeID)
</div>
<br />
<div>
#Html.Label("Room Type Name")
</div>
<div>
#Html.EditorFor(model => model.RoomTypeName)
#Html.ValidationMessageFor(model => model.RoomTypeName)
</div>
<br />
<div>
#Html.Label("Room Type Description")
</div>
<div>
#Html.TextAreaFor(model => model.RoomTypeDescription)
#Html.ValidationMessageFor(model => model.RoomTypeDescription)
</div>
<br />
<table>
<thead>
<tr>
<th>Facility Name</th>
<th> is available</th>
</tr>
</thead>
<tbody>
#foreach (var facility in Model.facilitiesInRoom)
{
<tr>
<td>
#(facility.RoomFacilityName)
</td>
<td style="text-align:center;">
<input type="checkbox" #(facility.RoomFacilityAvailable ? " checked=checked" : null) name="FacilityIDs" value="#facility.RoomFacilityID" />
</td>
</tr>
}
</tbody>
</table>
<br />
<p>
<input type="submit" value="Save" />
<input style="width:100px;" type="button" title="EditHotelDetail" value="Back to Detail" onclick="location.href='#Url.Action("Room", "Hotel") '" />
</p>
</fieldset>
}
My method
public List<ShowEditRoomViewModel> showNewRooms()
{
List<RoomType> roomTypes = (from d in _RoomTypeRepository.All()
select d).ToList();
List<ShowEditRoomViewModel> showEditRoomViewModel = new List<ShowEditRoomViewModel>();
foreach (RoomType roomType in roomTypes)
{
showEditRoomViewModel.Add(new ShowEditRoomViewModel
{
RoomTypeID = roomType.RoomTypeID,
facilitiesInRoom = LoadFacilityInRoom()
});
}
return showEditRoomViewModel;
}
can someone tell me, where is my mistake??
thanks
When you are inserting RoomtypeId in Database, you are using ExecuteNonQuery() method, It will always return 1 whenever you insert a new record in it,
If you are using stored procedure for inserting,you can use
select Scope_identity()
after insertion.

Resources