I'm building the third more or less identical form in an MVC project (meaning I'm copying and pasting to save time). This new form, with only one control is throwing a null reference error on the #Html.AntiForgeryToken() line.
View:
#model SubSheets.ViewModels.TaskItemViewModel
#using (Html.BeginForm("CreateTaskItem", "TaskItems"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => m.Name, "Task Name", new {#class = "control-label col-md-2"})
<div class="col-md-2">
#Html.EditorFor(m => m.Name, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(m => m.Name, "", new {#class = "text-danger"})
</div>
</div>
</div>
}
Controller:
[Authorize]
[HttpPost]
public ActionResult CreateTaskItem(TaskItemViewModel viewModel)
{
/* db context actions */
return View("../WorkItems/CreateWorkItem");
}
The form posts just fine, the data is saved just fine as well. However I get a null reference error, line 13:
Object reference not set to an instance of an object.
Line 11: #using (Html.BeginForm())
Line 12: {
Line 13: #Html.AntiForgeryToken()
Line 14:
Line 15: <div class="form-horizontal">
I thought I understood the Html helper adds a hidden form field that makes sure Post request isn't coming from a third-party domain. I didn't expect to get a null reference exception from a form field?
I had the same thing recently. It wasn't that the model hadn't been initialised and sent to the view; instead, it was due to a ViewData[] item not being initialised, but the error appeared on the #Html.AntiForgeryToken() line which threw me for a while.
Related
I am working on ASP.Net MVC 4.7.2 app. It has a date field where user can select or type the date. If user enter the date with year yyyyy (the length of year is greater than 4 here)then the error shows up which show the date in 'yyyy/mm/dd' format instead of 'mm/dd/yyyy' format. See the screen shot below.
I want to show the same format in the error message as mm/dd/yyyy'. To fix the issue I did search and it seemed this is generated from kendu whereas I am not using the kendu control for date field. As a work around, I thought I can limit the max length but that did not work as well.
View html:
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-xs-2" })
<div class="col-xs-8">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
I try some research and seem like it's hard to change the error message with the right format. You can update the error message to "Please enter a valid date" or "Please enter a valid date with format mm/dd/yyyy"
#Html.EditorFor(model => model.Name, new
{
htmlAttributes = new { #class = "form-control" },
data_val_date = String.Format("Please enter a valid date",
Html.DisplayNameFor(model => model.Name))
})
Tried calling the new column I made in my database via Razor, throwing an error in a different file. I am completely unsure what any of this means.
Server Error in '/' Application.
Invalid column name 'ProductImage'.
Description: An unhandled exception occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'ProductImage'.
Source Error:
Line 19: {
Line 20: var products = db.Products.Include(p => p.Supplier);
Line 21: return View(products.ToList());
Line 22: }
Line 23:
Here is where I am calling on the item in Razor (my Index view of my controller that I added the new column in)
#foreach (var item in Model)
{
<tr>
<td>
<div class="col-lg-4 col-sm-6">
<div class="single_category_product">
<div class="single_category_img">
<img src="~/Content/img/storefront/#item.ProductImage" alt="">
<div class="category_social_icon">
<ul>
<li><i class="ti-heart"></i></li>
<li><i class="ti-bag"></i></li>
</ul>
</div>
<div class="category_product_text">
<h5>#Html.DisplayFor(x => item.Name)</h5>
<p>#Html.DisplayFor(x => item.Price)</p>
</div>
</div>
</div>
</div>
</td>
<td>
#Html.ActionLink("Details", "Details", new { id = item.ProductID })
#if (User.IsInRole("Admin"))
{
#Html.ActionLink("Edit", "Edit", new { id = item.ProductID })
#Html.ActionLink("Delete", "Delete", new { id = item.ProductID })
}
</td>
</tr>
}
I am trying to pass two parameters through a #Url.Action for a submit button. However, the values are not being passed.
I have index view with a dropdown field and a Save button. What I would like for the user to be able to do is select a dropdown value and Save the value. However, no matter how I access my function the values are null. I have tried passing in parameters and binding the data.
Currently my view looks like -
<h3>Burn Conditions</h3>
<div class="form-group">
#Html.LabelFor(model => model.ConditionsReasonsID, "Condition", new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.DropDownList("ConditionsReasonsID", String.Empty)
#ViewBag.conditionsReasons
#Html.ValidationMessageFor(model => model.ConditionsReasonsID)
<a href= "#Html.Raw(#Url.Action("CreateCondition", "RequestedBurns", new { requestedBurnsID = ViewBag.RequestedBurnsID, conditionsReasonsID = Model.ConditionsReasonsID }))">
<input type="submit" value="Save Condition" />
</a>
</div>
</div>
in my controller I have
public ActionResult CreateCondition(int requestedBurnsID, int conditionsReasonsID)
{
BurnDecision burnDecision = new BurnDecision();
burnDecision.RequestedBurnsID = requestedBurnsID;
burnDecision.ConditionsReasonsID = conditionsReasonsID;
//Find BurnSiteID
RequestedBurn requestedBurn = db.RequestedBurns.Find(burnDecision.RequestedBurnsID);
ViewBag.burnSitesID = requestedBurn.BurnSitesID;
db.BurnDecisions.Add(burnDecision);
db.SaveChanges();
return RedirectToAction("Index", "RequestedBurns", new { burnSitesID = ViewBag.burnSitesID, requestedBurnsID = burnDecision.RequestedBurnsID });
}
My project is Room-reservation service .I have View :
#model Client
#using (Html.BeginForm("SaveUserDB", "Booking", FormMethod.Post))
{
<div class="editor-label">
#Html.Label("Surname")
#Html.TextBoxFor(model => model.Surname)
</div>
<div class="editor-label">
#Html.Label("Name")
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.Label("Patronymic")
#Html.TextBoxFor(model => model.Patronymic)
</div>
<input type="submit" id="submit" value="Reservation" />
And I have controller for this View:
[HttpPost]
public ActionResult SaveUserDB(Client client)
{
if (ModelState.IsValid)
{
using (db)
{
db.Client.Add(client);
db.SaveChanges();
return RedirectToAction("Thankyou");
}
}
return View(client);
}
This controller save data client to database table Client. But I need also create record in second table Reservation, which takes parameters: Datetime.Now , and Client.Id. Parameter Client Id in database is autoincrement, but doesn't display in the View.
Well, if this is how you add a record to the Client table:
db.Client.Add(client);
Then why not use that same exact approach to add a record to the Reservation table? Something like this:
var reservation = new Reservation
{
ClientID = client.ID,
SomeOtherColumn = DateTime.Now
};
db.Reservation.Add(reservation);
(Note: This is based on speculation of what your Reservation object/table might look like based on your description. But the concept is the same. Create an instance of a reservation object and add it to the data context.)
I hope there is a simple answer to this problem which I'm just not seeing.
I am developing an asp.net MVC 4 application.
Basically I want to allow the user to edit the contents of a previous entry(newsArticle) they would have made (sounds easy)
This entry consist's of a date, two blocks of text, (Title and body) an img.
These entries correspond to properties of a model, which also include, ID , img name and status.
I have successfully manged to enter, save and retrieve all the data when needed.
However when I run the program and try and edit a previous entry it only saves the Title and the body text and removes the values that were there, for date, img, img name and status.
Is this related to the textboxes used in the view ? Why are those values kept and the others not.
Just to point out when I run and select an entry all the data is shown correctly but when I click save values are removed (date, img name , status)
Any thoughts.....
Controller....
public ActionResult Edit(int id)
{
String encodedBody;
NewsArticle newsArticle = _newsArticle.Get(id);
encodedBody = HttpUtility.HtmlDecode(newsArticle.Body.ToString());
newsArticle.Body = encodedBody;
return View(newsArticle);
}
// POST: /Article/Edit/5
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle)
{
try
{
if (ModelState.IsValid)
{
db.Entry(newsArticle).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (System.Data.DataException)
{
//Log th error(add a variable name after DataExpection)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(newsArticle);
}
View.......
#using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal", id = "newsEditForm"}))
{
#Html.ValidationSummary()
#Html.HiddenFor(model => model.ID)
<div class="control-group">
<label class="control-label">Posted on :</label>
<div class="controls">
<span class="text">#Model.DateCreated.Value.ToShortDateString()</span>
#*#Html.LabelFor(n => n.DateCreated)*#
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.LabelFor(n => n.Title)</label>
<div class="controls">
#Html.TextBoxFor(n => n.Title, new { #class = "span4 m-wrap", rows = 1})
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.LabelFor(n => n.Body)</label>
<div class="controls">
#Html.TextAreaFor(n => n.Body, new { #class = "span12 ckeditor m-wrap", rows = 4 })
</div>
</div>
<div class="control-group">
<label class="control-label">Selected Image </label>
<label class="controls">#Html.DisplayTextFor(model => model.ImageName)</label>
#* <div class="span4 blog-img blog-tag-data">
<div class="editor-field">
<input type="file" name="Article" id="ArticleImage"/>
</div>
</div>*#
</div>
<div class="form-actions">
<button type="submit" class="btn green" id="submitnews"><i class="icon-ok"></i>Submit</button>
#Html.ActionLink("Cancel", "ArticleList", "Admin", null, new { #class = "btn blue"})
#*<button type="button" class="btn blue" onclick="location.href='ArticleList','Admin'">Cancel</button>*#
</div>
}
Your problem is you're saving the newsArticle that's posted back directly to the DB. The posted newsArticle contains a null entry for the image, date, img name and status because those fields don't exist in your form. You really shouldn't pass domain models back to your edit for this and other security reasons. However, this is a quick fix to your issue
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle)
{
try
{
if (ModelState.IsValid)
{
NewsArticle savedArticle= _newsArticle.Get(newsArticle.Id);
savedArticle.Body = newsArticle.Body
savedArticle.Title = newsArticle.Title
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (System.Data.DataException)
{
//Log th error(add a variable name after DataExpection)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(newsArticle);
}