I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.
e.g.
public class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
}
public class RegisterViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Do I need to make another ViewModel which holds these 2 ViewModels?
public BigViewModel
{
public LoginViewModel LoginViewModel{get; set;}
public RegisterViewModel RegisterViewModel {get; set;}
}
I need the validation attributes to be brought forward to the view. This is why I need the ViewModels.
Isn't there another way such as (without the BigViewModel):
#model ViewModel.RegisterViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Name)
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
#model ViewModel.LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
There are lots of ways...
with your BigViewModel
you do:
#model BigViewModel
#using(Html.BeginForm()) {
#Html.EditorFor(o => o.LoginViewModel.Email)
...
}
you can create 2 additional views
Login.cshtml
#model ViewModel.LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
and register.cshtml same thing
after creation you have to render them in the main view and pass them the viewmodel/viewdata
so it could be like this:
#{Html.RenderPartial("login", ViewBag.Login);}
#{Html.RenderPartial("register", ViewBag.Register);}
or
#{Html.RenderPartial("login", Model.LoginViewModel)}
#{Html.RenderPartial("register", Model.RegisterViewModel)}
using ajax parts of your web-site become more independent
iframes, but probably this is not the case
I'd recommend using Html.RenderAction and PartialViewResults to accomplish this; it will allow you to display the same data, but each partial view would still have a single view model and removes the need for a BigViewModel
So your view contain something like the following:
#Html.RenderAction("Login")
#Html.RenderAction("Register")
Where Login & Register are both actions in your controller defined like the following:
public PartialViewResult Login( )
{
return PartialView( "Login", new LoginViewModel() );
}
public PartialViewResult Register( )
{
return PartialView( "Register", new RegisterViewModel() );
}
The Login & Register would then be user controls residing in either the current View folder, or in the Shared folder and would like something like this:
/Views/Shared/Login.cshtml: (or /Views/MyView/Login.cshtml)
#model LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
/Views/Shared/Register.cshtml: (or /Views/MyView/Register.cshtml)
#model ViewModel.RegisterViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Name)
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
And there you have a single controller action, view and view file for each action with each totally distinct and not reliant upon one another for anything.
Another way is to use:
#model Tuple<LoginViewModel,RegisterViewModel>
I have explained how to use this method both in the view and controller for another example: Two models in one view in ASP MVC 3
In your case you could implement it using the following code:
In the view:
#using YourProjectNamespace.Models;
#model Tuple<LoginViewModel,RegisterViewModel>
#using (Html.BeginForm("Login1", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple => tuple.Item2.Name, new {#Name="Name"})
#Html.TextBoxFor(tuple => tuple.Item2.Email, new {#Name="Email"})
#Html.PasswordFor(tuple => tuple.Item2.Password, new {#Name="Password"})
}
#using (Html.BeginForm("Login2", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple => tuple.Item1.Email, new {#Name="Email"})
#Html.PasswordFor(tuple => tuple.Item1.Password, new {#Name="Password"})
}
Note that I have manually changed the Name attributes for each property when building the form. This needs to be done, otherwise it wouldn't get properly mapped to the method's parameter of type model when values are sent to the associated method for processing. I would suggest using separate methods to process these forms separately, for this example I used Login1 and Login2 methods. Login1 method requires to have a parameter of type RegisterViewModel and Login2 requires a parameter of type LoginViewModel.
if an actionlink is required you can use:
#Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id })
in the controller's method for the view, a variable of type Tuple needs to be created and then passed to the view.
Example:
public ActionResult Details()
{
var tuple = new Tuple<LoginViewModel, RegisterViewModel>(new LoginViewModel(),new RegisterViewModel());
return View(tuple);
}
or you can fill the two instances of LoginViewModel and RegisterViewModel with values and then pass it to the view.
Use a view model that contains multiple view models:
namespace MyProject.Web.ViewModels
{
public class UserViewModel
{
public UserDto User { get; set; }
public ProductDto Product { get; set; }
public AddressDto Address { get; set; }
}
}
In your view:
#model MyProject.Web.ViewModels.UserViewModel
#Html.LabelFor(model => model.User.UserName)
#Html.LabelFor(model => model.Product.ProductName)
#Html.LabelFor(model => model.Address.StreetName)
Do I need to make another view which holds these 2 views?
Answer:No
Isn't there another way such as (without the BigViewModel):
Yes, you can use Tuple (brings magic in view having multiple model).
Code:
#model Tuple<LoginViewModel, RegisterViewModel>
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple=> tuple.Item.Name)
#Html.TextBoxFor(tuple=> tuple.Item.Email)
#Html.PasswordFor(tuple=> tuple.Item.Password)
}
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple=> tuple.Item1.Email)
#Html.PasswordFor(tuple=> tuple.Item1.Password)
}
Add this ModelCollection.cs to your Models
using System;
using System.Collections.Generic;
namespace ModelContainer
{
public class ModelCollection
{
private Dictionary<Type, object> models = new Dictionary<Type, object>();
public void AddModel<T>(T t)
{
models.Add(t.GetType(), t);
}
public T GetModel<T>()
{
return (T)models[typeof(T)];
}
}
}
Controller:
public class SampleController : Controller
{
public ActionResult Index()
{
var model1 = new Model1();
var model2 = new Model2();
var model3 = new Model3();
// Do something
var modelCollection = new ModelCollection();
modelCollection.AddModel(model1);
modelCollection.AddModel(model2);
modelCollection.AddModel(model3);
return View(modelCollection);
}
}
The View:
enter code here
#using Models
#model ModelCollection
#{
ViewBag.Title = "Model1: " + ((Model.GetModel<Model1>()).Name);
}
<h2>Model2: #((Model.GetModel<Model2>()).Number</h2>
#((Model.GetModel<Model3>()).SomeProperty
a simple way to do that
we can call all model first
#using project.Models
then send your model with viewbag
// for list
ViewBag.Name = db.YourModel.ToList();
// for one
ViewBag.Name = db.YourModel.Find(id);
and in view
// for list
List<YourModel> Name = (List<YourModel>)ViewBag.Name ;
//for one
YourModel Name = (YourModel)ViewBag.Name ;
then easily use this like Model
My advice is to make a big view model:
public BigViewModel
{
public LoginViewModel LoginViewModel{get; set;}
public RegisterViewModel RegisterViewModel {get; set;}
}
In your Index.cshtml, if for example you have 2 partials:
#addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
#model .BigViewModel
#await Html.PartialAsync("_LoginViewPartial", Model.LoginViewModel)
#await Html.PartialAsync("_RegisterViewPartial ", Model.RegisterViewModel )
and in controller:
model=new BigViewModel();
model.LoginViewModel=new LoginViewModel();
model.RegisterViewModel=new RegisterViewModel();
I want to say that my solution was like the answer provided on this stackoverflow page: ASP.NET MVC 4, multiple models in one view?
However, in my case, the linq query they used in their Controller did not work for me.
This is said query:
var viewModels =
(from e in db.Engineers
select new MyViewModel
{
Engineer = e,
Elements = e.Elements,
})
.ToList();
Consequently, "in your view just specify that you're using a collection of view models" did not work for me either.
However, a slight variation on that solution did work for me. Here is my solution in case this helps anyone.
Here is my view model in which I know I will have just one team but that team may have multiple boards (and I have a ViewModels folder within my Models folder btw, hence the namespace):
namespace TaskBoard.Models.ViewModels
{
public class TeamBoards
{
public Team Team { get; set; }
public List<Board> Boards { get; set; }
}
}
Now this is my controller. This is the most significant difference from the solution in the link referenced above. I build out the ViewModel to send to the view differently.
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TeamBoards teamBoards = new TeamBoards();
teamBoards.Boards = (from b in db.Boards
where b.TeamId == id
select b).ToList();
teamBoards.Team = (from t in db.Teams
where t.TeamId == id
select t).FirstOrDefault();
if (teamBoards == null)
{
return HttpNotFound();
}
return View(teamBoards);
}
Then in my view I do not specify it as a list. I just do "#model TaskBoard.Models.ViewModels.TeamBoards" Then I only need a for each when I iterate over the Team's boards. Here is my view:
#model TaskBoard.Models.ViewModels.TeamBoards
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Team</h4>
<hr />
#Html.ActionLink("Create New Board", "Create", "Board", new { TeamId = #Model.Team.TeamId}, null)
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => Model.Team.Name)
</dt>
<dd>
#Html.DisplayFor(model => Model.Team.Name)
<ul>
#foreach(var board in Model.Boards)
{
<li>#Html.DisplayFor(model => board.BoardName)</li>
}
</ul>
</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.Team.TeamId }) |
#Html.ActionLink("Back to List", "Index")
</p>
I am fairly new to ASP.NET MVC so it took me a little while to figure this out. So, I hope this post helps someone figure it out for their project in a shorter timeframe. :-)
Create one new class in your model and properties of LoginViewModel and RegisterViewModel:
public class UserDefinedModel()
{
property a1 as LoginViewModel
property a2 as RegisterViewModel
}
Then use UserDefinedModel in your view.
you can always pass the second object in a ViewBag or View Data.
This is a simplified example with IEnumerable.
I was using two models on the view: a form with search criteria (SearchParams model), and a grid for results, and I struggled with how to add the IEnumerable model and the other model on the same view. Here is what I came up with, hope this helps someone:
#using DelegatePortal.ViewModels;
#model SearchViewModel
#using (Html.BeginForm("Search", "Delegate", FormMethod.Post))
{
Employee First Name
#Html.EditorFor(model => model.SearchParams.FirstName,
new { htmlAttributes = new { #class = "form-control form-control-sm " } })
<input type="submit" id="getResults" value="SEARCH" class="btn btn-primary btn-lg btn-block" />
}
<br />
#(Html
.Grid(Model.Delegates)
.Build(columns =>
{
columns.Add(model => model.Id).Titled("Id").Css("collapse");
columns.Add(model => model.LastName).Titled("Last Name");
columns.Add(model => model.FirstName).Titled("First Name");
})
...
)
SearchViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchViewModel
{
public IEnumerable<DelegatePortal.Models.DelegateView> Delegates { get; set; }
public SearchParamsViewModel SearchParams { get; set; }
....
DelegateController.cs:
// GET: /Delegate/Search
public ActionResult Search(String firstName)
{
SearchViewModel model = new SearchViewModel();
model.Delegates = db.Set<DelegateView>();
return View(model);
}
// POST: /Delegate/Search
[HttpPost]
public ActionResult Search(SearchParamsViewModel searchParams)
{
String firstName = searchParams.FirstName;
SearchViewModel model = new SearchViewModel();
if (firstName != null)
model.Delegates = db.Set<DelegateView>().Where(x => x.FirstName == firstName);
return View(model);
}
SearchParamsViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchParamsViewModel
{
public string FirstName { get; set; }
}
}
Here's the view I'm going to post:
#model WelcomeViewModel
#using (Html.BeginForm("SignUp", "Member", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
{
....
<div class="form-group">
#Html.EditorFor(model => model.SignUp.CompanyName, new {htmlAttributes = new {#class = "form-control" }})
</div>
<div class="form-group">
#Html.EditorFor(model => model.SignUp.RegisteredNo, new {htmlAttributes = new {#class = "form-control" } })
</div>
....
<button type="submit" name="signup" class="btn">Register</button>
}
ViewModel:
public class WelcomeViewModel
{
public SignInViewModel LogOn { get; set; }
public SignUpViewModel SignUp { get; set; }
}
Action method:
[HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
public virtual async Task<ActionResult> SignUp(SignUpViewModel model)
{
if (!ModelState.IsValid)
return View("SignIn", new WelcomeViewModel { SignUp = model });
// other code
return View();
}
When I post the data, the model gets null. I know the inputs will be generated like:
<input id="SignUp_CompanyName" name="SignUp.CompanyName">
But the model binder accepts this:
<input id="SignUp_CompanyName" name="CompanyName">
Now I want to know how can I remove that prefix? I know I can explicitly add name for each input:
#Html.TextBoxFor(model => model.SignUp.CompanyName, new { Name = "CompanyName" })
but I want to do it in a strongly type way.
Perhaps the easiest way would be to apply the [Bind] attribute with its Prefix set to "SignUp":
public async Task<ActionResult> SignUp([Bind(Prefix="SignUp")] SignUpViewModel model)
See MSDN
I must have something incorrectly setup as I can't get the UpdateModel function to correctly update my model based on information passed in via a FormCollection.
My View looks like:
#model NSLM.Models.Person
#{
ViewBag.Title = "MVC Example";
}
<h2>My MVC Model</h2>
<fieldset>
<legend>Person</legend>
#using(#Html.BeginForm())
{
<p>ID: #Html.TextBox("ID", Model.ID)</p>
<p>Forename: #Html.TextBox("Forename", Model.Forename)</p>
<p>Surname: #Html.TextBox("Surname", Model.Surname)</p>
<input type="submit" value="Submit" />
}
</fieldset>
My model is:
namespace NSLM.Models
{
public class Person
{
public int ID;
public string Forename;
public string Surname;
}
}
and my controller is:
[HttpPost]
public ActionResult Details(FormCollection collection)
{
try
{
// TODO: Add update logic here
Models.Person m = new Models.Person();
// This doesn't work i.e. the model is not updated with the form values
TryUpdateModel(m);
// This does work
int.TryParse(Request.Form["ID"], out m.ID);
m.Forename = Request.Form["Forename"];
m.Surname = Request.Form["Surname"];
return View(m);
}
catch
{
return View();
}
}
as you can see if I manually assign each property it works fine, so what have I not set that would get the model to be updated with the form values?
Thanks,
Mark
Replace fields with properties in your model, i.e.:
namespace NSLM.Models
{
public class Person
{
public int ID {get; set;}
public string Forename {get; set;}
public string Surname {get; set;}
}
}
By the time the call gets to the action method any automatic model binding has already been performed. Try changing the input parameter of your action method to accept a Person instance. In that case the model binder will try to create the instance and populate it from the values passed by your form.
try this :
view :
#model NSLM.Models.Person
#{
ViewBag.Title = "MVC Example";
}
<h2>My MVC Model</h2>
<fieldset>
<legend>Person</legend>
#using(#Html.BeginForm())
{
#Html.HiddenFor(model => model.ID)
<p>Forename: #Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</p>
<p>Surname: #Html.EditorFor(model => model.Surname)
#Html.ValidationMessageFor(model => model.Surname)
</p>
<input type="submit" value="Submit" />
}
</fieldset>
Controller :
[HttpPost]
public ActionResult Details(Person p)
{
if (ModelState.IsValid)
{
db.Entry(p).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(p);
}
I have mvc3 application in this i have used two partial views 1.controls 2.webgrid
inside controls i'm populating dropdownlists from actual database tables. using EF
On index.cshtml i have one form in which need to select values from these dropdown lists and when press insert button these values should have to go to Temp "DataTable" and also show it in webgrid...I'm newbie to MVC3 and dont know how to do this.
Controls.cshtml
#model Mapping.Models.SecurityIdentifierMappingViewModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Mapping</legend>
<div class="editor-label">
#Html.Label("Pricing SecurityID")
</div>
<div class="editor-field">
#Html.HiddenFor(model => model.MappingControls.Id)
#Html.DropDownListFor(model => model.MappingControls.PricingSecurityID,
new SelectList(Model.PricingSecurities, "Value", "Text"),
"Select SecurityID"
)
#Html.ValidationMessageFor(model => model.MappingControls.PricingSecurityID)
</div>
<div class="editor-label">
#Html.Label("CUSIP ID")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.MappingControls.CUSIP,
new SelectList(Model.CUSIPs, "Value", "Text"),
"Select CUSIP"
)
#Html.ValidationMessageFor(model => model.MappingControls.CUSIP)
</div>
<div class="editor-label">
#Html.Label("Calculation")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.MappingControls.Calculation)
#Html.ValidationMessageFor(model => model.MappingControls.Calculation)
</div>
<p>
<input id="btnsubmit" type="submit" value="Insert" />
</p>
</fieldset>
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
mydataEntities dbContext = new mydataEntities();
DataRepository objRepository = new DataRepository();
//GET
public ActionResult Index(string userAction , int uid = 0)
{
var mappingobj = new SecurityIdentifierMappingViewModel();
mappingobj.MappingWebGridList = dbContext.SecurityIdentifierMappings.ToList();
mappingobj.MappingControls = new SecurityIdentifierMapping();
mappingobj.MappingControls.PricingSecurityID = 0;
mappingobj.MappingControls.CUSIP = string.Empty;
mappingobj.PricingSecurities = objRepository.GetPricingSecurityID();
mappingobj.CUSIPs = objRepository.GetCUSIP();
return View(mappingobj);
}
//POST
[HttpPost]
public ActionResult Index(SecurityIdentifierMappingViewModel objModel)
{
if (objModel.MappingControls.Id > 0)
{
if (ModelState.IsValid)
{
dbContext.Entry(objModel.MappingControls).State = EntityState.Modified;
try
{
dbContext.SaveChanges();
//objModel = new SecurityIdentifierMappingViewModel();
//return RedirectToAction("Index", "Home");
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
throw;
}
}
}
//insert code
else
{
if (ModelState.IsValid)
{
dbContext.SecurityIdentifierMappings.Add(objModel.MappingControls);
try
{
dbContext.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
throw;
}
}
}
return RedirectToAction("Index");
}
}
public class SecurityIdentifierMappingViewModel
{
public IEnumerable<SecurityIdentifierMapping> MappingWebGridList { get; set; }
public SecurityIdentifierMapping MappingControls { get; set; }
public List<SelectListItem> PricingSecurities { get; set; }
public List<SelectListItem> CUSIPs { get; set; }
}
Currently using SecurityIdentifierMapping as a 3rd table from database in which inserting my form data ... but need to insert it into "DataTable"
You will have to create a DataTable object and assign appropriate DataColumn objects to it. After that map your SecurityIdentifierMapping properties to columns in your temporary data table. As for mapping DataTable to WebGrid, I am not going to say that it is not possible as I have never tried this thing personally, but you will have to map it back to a collection of SecurityIdentifierMapping.
But, why do you need DataTable? What possible advantages could DataTable have over IQueryable or IEnumerable? What is it that you actually want to achieve using this strategy?
UPDATE:
You are already using IEnumerable in your ViewModel class (SecurityIndentifierMappingViewModel). At the same time you are storing data in the database when POSTing to Index, and fetching again in GET version of Index.
What you are missing is to create a WebGrid object in your view. Your view could be defined like this:
#{
var columns = new List<string>();
columns.Add("Column 1");
columns.Add("Column 2");
var grid = new WebGrid(model: Model.MappingWebGridList, columnNames: columns);
}
#grid.GetHtml()
Place the above code somewhere in your Index view, and define your own columns. In addition, have a look at this article which I wrote in order to get more ideas what you can do with WebGrid http://apparch.wordpress.com/2012/01/04/webgrid-in-mvc3/.
I hope I managed to help you at least a bit.
In my MVC program, once the user has submitted an edit form, those values for the object get saved in the model server-side, but the previous values show up in the view.
I know it has to do with MVC's validation process, where it first checks ModelState before the server side values. The solution I've read across the forums is to clear the ModelState. The only problem is, ModelState.Clear isn't working for me.
Help please.
Model
public class Help
{
[HiddenInput(DisplayValue=true)]
public int HelpID { get; set; }
[Required(ErrorMessage = "Please enter a proper URL")]
public string URL { get; set; }
[Required(ErrorMessage = "Please enter a content description:")]
[DataType(DataType.MultilineText)]
public string HelpContent { get; set; }
/*? 2 properites are nullable*/
public DateTime? createDateTime { get; set; }
public DateTime? modifiedDateTime { get; set; }
}
Controller
/*Create the admin controller*/
public class AdminController : Controller
{
//declare interface object
private IHelpRepository repository;
/*Pass a db interface to controller*/
public AdminController(IHelpRepository repo)
{
repository = repo;
}
/*default admin screen. displays help table obs*/
public ViewResult Index()
{
return View();
}
/*Returns add view form*/
public ActionResult AddForm()
{
return PartialView();
}
/*Will handle the post for the add screen after user has
submitted add information*/
[HttpPost]
[ValidateInput(false)] //this allows admin to place html in field
public ActionResult AddForm(Help help)
{
if (ModelState.IsValid) //if all fields are validated
{
//set the edit date
help.createDateTime = DateTime.Now;
repository.SaveHelp(help);
return (null); //return "null" to div so control is given back to main view
}
else //there is something wrong. send back to view
{
return PartialView(help);
}
}
/*Returns edit view form, searches for object to edit with id
if no id provided, 0 by default*/
public ActionResult EditForm(int helpID = 0)
{
Help help = repository.Help.FirstOrDefault(q => q.HelpID == helpID);
help.HelpContent = System.Web.HttpUtility.HtmlDecode(help.HelpContent);
return PartialView(help);
}
/*Will handle the post for the edit screen after user has
submitted edit information*/
[HttpPost]
[ValidateInput(false)] //this allows admin to place html in field
public ActionResult EditForm(Help help)
{
if (ModelState.IsValid) //if all fields are validated
{
//set the edit date
help.modifiedDateTime = DateTime.Now;
repository.SaveHelp(help);
ModelState.Clear();
return (null); //return "null" to div so control is given back to main view
}
else //there is something wrong. send back to view
{
return PartialView(help);
}
}
/*Delete action method, searches with id*/
[HttpPost]
public ActionResult Delete(int helpId)
{
Help helpDel = repository.Help.FirstOrDefault(p => p.HelpID == helpId);
if (helpDel != null) //if the object is found, delete
{
repository.DeleteHelp(helpDel);
}
//in all cases return to index
return RedirectToAction("Index");
}
/*Used by the telerik table to rebind grid*/
[GridAction]
public ActionResult AjaxBinding()
{
return View(new GridModel(repository.Help));
}
}//end admin controller class`
Partial View (Gets loaded into a div)
`
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "Editx" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Edit Entry</legend>
#Html.HiddenFor(model => model.HelpID)
<div class="editor-label">
#Html.LabelFor(model => model.URL)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.URL)
#Html.ValidationMessageFor(model => model.URL)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HelpContent, "Help Content")
</div>
<div class="editor-field">
#{
Html.Telerik().EditorFor(content => content.HelpContent)
.Name("HelpContent")
.FileBrowser(settings => settings
.Browse("Browse", "ImageBrowser")
.Thumbnail("Thumbnail", "ImageBrowser")
.Upload("Upload", "ImageBrowser")
.DeleteFile("DeleteFile", "ImageBrowser")
.DeleteDirectory("DeleteDirectory", "ImageBrowser")
.CreateDirectory("CreateDirectory", "ImageBrowser")
)
.Render();
}
#Html.ValidationMessageFor(model => model.HelpContent)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.createDateTime, "Create Date")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.createDateTime)
#Html.ValidationMessageFor(model => model.createDateTime)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.modifiedDateTime, "Modified Date")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.modifiedDateTime)
#Html.ValidationMessageFor(model => model.modifiedDateTime)
</div>
<p>
<input id="btnEdit" type="submit" value="Save" />
<button id="btnCancel">Cancel</button>
</p>
</fieldset>
}
After trolling through about a hundred links, I found the solution to my problem. ModelState.Clear actually clears the objects values in the controller, but for whatever reason was still displaying the old values in the view. Maybe its because I load/unload my edit form into a div tag? Don't ask. I don't know. The solution that works for me is this:
$.ajax({
url: "somecontroller/someAction,
cache: false, // this is key to make sure JQUERY does not cache your request
success: function( data ) {
alert( data ); } });
I had to set the "cache" setting to "false".
Thanks to #minus4 for the solution, bruh.