Data not displaying without model null check..Why? - asp.net-mvc

I am using MVC4 Razor
Controller--
[HttpPost]
public ActionResult FillLogin(LoginModel model)
{
if (ModelState.IsValid)
{
if (model.username == "password")
{
string x = model.getdata();
model.field1= "Hello";
return View(model);
}
}
return View(model);
}
In view i am not getting the Data Displayed when i tried like
#Html.TextBoxFor(m => m.field1)
But working Fine if Given like
#if (Model != null )
{
#Html.TextBoxFor(m => m.field1)
}
Can anyone help me why this happens....I am new to MVC

Model should never be null. And I suspect that the problem is in the GET action not in the POST one. ALWAYS return a new instance of the model
public ActionResult FillLogin()
{
return View(new LoginModel());
}

Related

MVC Form DropDownListFor

In my view I am building a form where the user select a country from a list of Countries.I get this error about Object reference not set to an instance of an object. Is there anything I am missing?
#Html.DropDownListFor(
x => x.selectedCountryId,
new SelectList(Model.ListOfCountries, "Value", "Text"),
"-- please select a Country--",
new { id = "ddlCountry", #class = "form-control" }
)
#Html.ValidationMessageFor(x => x.selectedCountryId)
Model
[Required]
public int? selectedCountryId{ get; set; }
Error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Web.Mvc.WebViewPage<TModel>.Model.get returned null.
Action Method
public ActionResult Create(RequestFormViewModel model)
{
if (!ModelState.IsValid)
{
}
return View(TemplateName, "");
public ActionResult Index()
{
RequestFormViewModel result = new RequestFormViewModel ();
try
{
var FormInfo = GetFormInfo();
if (FormInfo != null)
{
result = FormInfo;
}
}
catch (Exception e)
{
}
return View(TemplateName, result);
}
Your action methods should be like below
[HttpGet]
public IActionResult Create()
{
//Way 1
RequestFormViewModel model = new RequestFormViewModel();
model.ListOfCountries = //Select from DB or Whatever
return View(model);
//Way 2
ViewBag.ListOfCountries = //Select from DB or Whatever
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RequestFormViewModel model)
{
if (ModelState.IsValid)
{
}
return View(model);
}
and for view if you will use way 1 so you need to add ListOfCountries as [NotMapped] to your model or create Dto for this view
for way2 you need to bind dropdown from ViewBag instead of using ListOfCountries as a property

Telerik ASP.NET Grid Column Template Issues

I want to put a link in my Telerik grid that will call an Edit action in my Contact controller. The code that I have puts the link in its respective place but gives me a 400 Bad Request Error. I have a feeling that there is a problem with the syntax behind my columns.Template code.
Here is the Index view
columns.Template(
#<text>
#Html.ActionLink("Edit", "Edit", new { id = item.ContactId })
</text>
).ClientTemplate(#"View");
Here is the ContactController
// GET: Client/Edit/5
public ActionResult Edit(int? id)
{
using (var provosity = new ProvosityContext())
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
Contact contact = provosity.Contacts.Find(id);
if (contact == null)
return HttpNotFound();
return View(contact);
}
}
// POST: Client/Edit/5
[HttpPost]
public ActionResult Edit(Contact contact)
{
try
{
using (var provosity = new ProvosityContext())
if (ModelState.IsValid)
{
provosity.Entry(contact).State=System.Data.Entity.EntityState.Modified;
provosity.SaveChanges();
return RedirectToAction("Index");
}
return View(contact);
}
catch
{
return View();
}
}
}
}
Here goes like i do:
c.Bound(p => p.ContactId).ClientTemplate("View");

MVC how reload page keeping the data in textbox

(MVC)How to RedirectToAction and keep the content of a Html.Textbox in MVC4? This is my controller how do I fix it and what goes in the view?
[HttpPost]
public ActionResult Index(string ssn)
{
var exist = false;
var record = _db.Citations.Where(u => u.SSN == ssn).FirstOrDefault();
if (record != null)
{
exist = true;
return RedirectToAction("EditDetails", new { id = record.CitationID });
}
else
{
return RedirectToAction("Index", "SubmitAward", ssn); // wiped out ssn! I need to keep the ssn
// so that the user can fill out the form.
}
If your get action is like this:
public ActionResult Index(string ssn)
{
.........
..........
.........
}
then do like this:
return RedirectToAction("Index", "SubmitAward", new { ssn = ssn});
but if it is the same index view of post action which is posted in question, you can pass the object back to view if your view is strongly typed to this class:
return View(record);
Try below code
return RedirectToAction("Index", "SubmitAward", new { ssn = ssn});
And your redirect action will be
public ActionResult Index(string ssn)
{
ViewBag.SSN=ssn;
return View(record);
}
And your view will contain textbox like
#Html.TextBox("SSN",ViewBag.SSN)
It may helps you..

Set Html.TextBox value to null

I have the following textbox on an MVC view:
#Html.TextBoxFor(x => x.Captcha, new { #value = "" })
I am trying the textbox to always be empty when the form show after being submited with errors ... But this is not working. I always see the last value.
And this is my controller:
[Route("signup"), HttpGet]
public virtual ActionResult SignUp() {
UserSignUpModel model = new UserSignUpModel();
model.Captcha = String.Empty;
model.Email = "";
return View(model);
} // SignUp
[Route("signup"), HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult SignUp(UserSignUpModel model) {
if (ModelState.IsValid) {
// Create account code
return View(MVC.Shared.Views._Note, new NoteModel("Account created"));
} else {
model.Captcha = String.Empty;
model.Email = "";
return View(Views.SignUp, model);
}
}
Thank You,
Miguel
If your form is submitted with errors, you can simply clear the ViewData and explicitly clear your property in the controller before returning the view with errors.
[HttpPost]
public ActionResult MyController(Model myModel)
{
if (!ModelState.IsValid)
{
myModel.Captcha = String.Empty;
ViewData = null;
return View(myModel);
}
return View(myModel);
}
I was able to solve this. The correct way is to use the model state:
ModelState["Captcha"].Value = new ValueProviderResult("", "", Thread.CurrentThread.CurrentCulture);
This way there is no need to clear other data in ViewData.
And by changing the ModelState, and not removing it, it becomes possible to still display the error associated with that property.
In your action method in your controller set this parameter manually:
// ...
model.Captcha = String.Empty;
return View(model);
And I recommend to add autocomplete=off html attribute to your captcha field:
#Html.TextBoxFor(x => x.Captcha, new { autocomplete = "off" })

Display the same page after saving

I'd like show a form with some field (one in the example), submit it, save and display the same page with a reset of all fields. The probelm when I submit, I go the "Save" action but when I display the view the form is still filled in.
The model :
public class TestingModel
{
public string FirstName { get; set; }
}
The controller :
public class ChildController : Controller
{
public ActionResult Index()
{
TestingModel model = new TestingModel();
return View(model);
}
public ActionResult Save(TestingModel model)
{
Console.WriteLine(model.FirstName); //OK
//Save data to DB here ...
TestingModel testingModel = new TestingModel() { FirstName = string.Empty };
return View("Index", testingModel);
}
}
The view :
#using (Html.BeginForm("Save", "Child",FormMethod.Post))
{
#Html.TextBoxFor( m => m.FirstName)
<input type="submit" id="btSave" />
}
When Id debug to the view, in "Immediat window" Model.FirstName = "" but when the page is show I still have the value posted. I tried a ReditrectionToAction("Index") at the end of the Save method but same result.
Do you have an idea ?
Thanks,
If you want to do this you need to clear everything that's in the ModelState. Otherwise HTML helpers will completely ignore your model and use data from ModelState when binding their values.
Like this:
[HttpPost]
public ActionResult Save(TestingModel model)
{
//Save data to DB here ...
ModelState.Clear();
TestingModel testingModel = new TestingModel() { FirstName = string.Empty };
return View("Index", testingModel);
}
or simply redirect to the Index GET action in case of success:
[HttpPost]
public ActionResult Save(TestingModel model)
{
//Save data to DB here ...
return RedirectToAction("Index");
}
Try to return Index view without any model
return View("Index");
You should be posting your form back to the same ActionResult
public ActionResult Index()
{
TestingModel model = new TestingModel();
return View(model);
}
[HttpPost]
public ActionResult Index(TestingModel model)
{
Console.WriteLine(model.FirstName); //OK
//Save data to DB here ...
return RedirectToAction("Index");
}
You would be able to use the parameterless overload for BeginForm too
#using(Html.BeginForm())
{
//form
}

Resources