render partial view insted of other partial view - asp.net-mvc

I have a form which is a partial view in layout page. I need after success to render another partial view in the first one place.
However the partial view is rendered inside the first partial view. (for example if user fill the form in Mydomain/index the new partial view should display in the same url. And now it is displayed in /controller/create).
[ChildActionOnly]
public ActionResult Create()
{
ViewBag.SubjectId = new SelectList(db.subjects, "SubjectId", "Subjectname");
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "InfoId,FirstName,SureName,PhoneNumber,Address,Email,EnterdDate,IsActive,Tipol,SubjectId")] Info info)
{
info.EnterdDate = DateTime.Now;
info.IsActive = false;
if (ModelState.IsValid)
{
db.infos.Add(info);
db.SaveChanges();
TempData["thanks"] = info.FullName;
return PartialView("_bla");
}
ViewBag.SubjectId = new SelectList(db.subjects, "SubjectId", "Subjectname", info.SubjectId);
return View(info);
}
public PartialViewResult _bla()
{
var thanks = TempData["thanks"];
return PartialView();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "InfoId,FirstName,SureName,PhoneNumber,Address,Email,EnterdDate,IsActive,Tipol,SubjectId")] Info info)
{
info.EnterdDate = DateTime.Now;
info.IsActive = false;
if (ModelState.IsValid)
{
db.infos.Add(info);
db.SaveChanges();
TempData["thanks"] = info.FullName;
return RedirectToAction("Create");
}
ViewBag.SubjectId = new SelectList(db.subjects, "SubjectId", "Subjectname", info.SubjectId);
return View(info);
}
View Create:
#if (TempData["thanks"] != null)
{
<div class="alert alert-success">
#TempData["thanks"]
</div>
}
// your form

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

Render partial view or view from controller

I'm trying to render from controller either PartialView or View depending on condition coming from outside. Web-site fails on posting data with StackOverflowException.
Controller code:
public ActionResult Login(bool partial = false)
{
if (partial)
{
ViewBag.Partial = true;
return PartialView();
}
return View();
}
[HttpPost]
public ActionResult Login(UserViewModel userViewModel)
{
if (!ModelState.IsValid)
return View(userViewModel);
// some authrorization staff
}
Login.cshtml:
#using SK.DDP.ImageGallery.Helpers
#model SK.DDP.ViewModels.UserViewModel
#{
ViewBag.Title = "Login";
if (ViewBag.Partial != null)
{
Layout = string.Empty;
}
}
#*Some form staff*#
AuthorizationInfo.cshtml:
#{
Layout = string.Empty;
}
#{ Html.RenderAction("Login", "Authorization"); }
Template:
#*Some dif for form requested by menu*#
#{ Html.RenderAction("AuthorizationInfo", "Authorization"); }
I have a web-site with login page and login popup window appearing when user clicks on menu, so i wanted to reuse the same action of controller and code and app is continuing to fail with stackoverflow exception.
Thanks.
Seems its a bug in a Razor engine.
I workarounded it.
AuthorizationInfo.cshtml
#{ Html.RenderAction("LoginPartial"); }
AuthorizationController.cs
public ActionResult Login()
{
return View();
}
public ActionResult LoginPartial()
{
ViewBag.Partial = true;
return PartialView("Login");
}
Now Post of forms does not generate overflows with templates applied recursively.

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..

Render and display a view from another controller

How can I call and render a view of controller from action of another controller.
I have this, an action of Product Controller :
public ActionResult SortedLists(List<string> items, string ShopID)
{
//Do sth...
db.SaveChanges();
return RedirectToAction("Index", "ControlPanel", new { ID = ShopID });
}
And Index is the action(view) of ControlPanel Controller :
public ActionResult Index(int ID)
{
ViewBag.theRelatedShopID = ID;
return View();
}
How can I render Index and display it in browser???
public ActionResult SortedLists(List<string> items, string ShopID)
{
//Do sth...
db.SaveChanges();
return View("~/ControlPanel/Index.cshtml", (object)ShopID);
}
Here we are passing the ShopId as model to the Index view. If this view is strongly typed to some model you should pass this model:
MyViewModel model = ...
return View("~/ControlPanel/Index.cshtml", model);

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