MVC3 custom server-side data annotation validation not working in partial view - asp.net-mvc-3

I am trying to add custom data validation via data annotations. I am only concerned about server-side validation at this point. Everything I have seen here and elsewhere references client-side validation. I've stripped down all my code, ran a few test cases and I can get this working just fine on a regular view but as soon as the form is in a partial view, the code no longer breaks in the method to override IsValid.
In either case I can see the custom attribute being initialized. When the form is in a regular view I can see the override method being executed upon submitting the form, but when in a partial view the code never gets executed and it goes right to the HttpPost action.
I have spent the better parts of two days trying to figure this out and am at a loss. Any help would be GREATLY appreciated.
Note:
The code below does return the same view when it enters the HttpPost action. I have it like this for testing purposes. I know my override is never getting called from the partial view and thus IsValid is always true.
View showing form where the validation works
#model eRecruitBoard.ViewModels.HomeIndexViewModel
#{
ViewBag.Title = "eRecruitBoard";
}
#*<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>*#
<h2>Login/homepage</h2>
<br /><br />
<div class="errorMessage">
#Html.DisplayFor(m => m.LoginErrorMsg)
</div>
<br />
#using (Html.BeginForm("Index", "Home")) {
<div id="loginControlBox">
<fieldset>
<legend>Welcome to eRecruitBoard</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<div class="editor-label">
#Html.EditorFor(m => m.Date)
#Html.ValidationMessageFor(m => m.Date)
</div>
<p>
<input type="submit" value="Log In" />
</p>
</fieldset>
</div>
}
<div>
#Html.Action("BlankForm", "TestForm")
</div>
Partial View (these script calls also come in via _Layout, but I had them here for testing as well)
#model eRecruitBoard.ViewModels.TestFormViewModel
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
#using (Html.BeginForm("NewActivity2", "TestForm", FormMethod.Post))
{
<fieldset>
<legend>Test Form</legend>
<br />
#Html.LabelFor(m => m.Date)
#Html.EditorFor(m => m.Date)
#Html.ValidationMessageFor(m => m.Date)
<input id="activityTimelineSubmit" type="submit" value="Submit" />
</fieldset>
}
ViewModel (for partial view)
namespace eRecruitBoard.ViewModels
{
public class TestFormViewModel
{
[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
[NonFutureDate()]
[Display(Name = "Date")]
public DateTime Date { get; set; }
}
}
Controller (for partial view)
namespace eRecruitBoard.Controllers
{
public class TestFormController :BaseController
{
public ActionResult BlankForm()
{
var viewModel = new TestFormViewModel
{
Date = DateTime.Today
};
return PartialView("_TestForm", viewModel);
}
[HttpPost]
public ActionResult NewActivity2(DateTime Date)
{
if (!ModelState.IsValid)
return RedirectToAction("Index", "Home");
else
return RedirectToAction("Index", "Home");
}
}
}
Validation code
using System;
using System.ComponentModel.DataAnnotations;
namespace eRecruitBoard.WebLibrary.Validation
{
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public class NonFutureDateAttribute : ValidationAttribute //public sealed class
{
public NonFutureDateAttribute(): base("Activity can only be saved for today or dates in the past.")
{
}
public override bool IsValid(object value)
{
DateTime dateToCheck = (DateTime)value;
return (dateToCheck <= DateTime.Today);
}
}
}

If you RedirectToAction you lose all validation. You have to return PartialView(model) in your POST action. That would require changing the parameter type of NewActivity2 to TestFormViewModel instead of DateTime.
Update your code with example of how you display the partial view (#Html.Partial() or javascript) if it still doesnt work.

Related

Call ActionResult from Ajax.BeginForm

I using Ajax begin form and when I click submit button, post method doesn't call, here is code:
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "personListDivforReturnPerson"}))
{
<div class="ReturnPersonGeneralPageBody">
<div class="returnPersonHeader">
საზღვრის კვეთისას დაფიქსირებული მონაცემები
</div>
<div class="fieldNameForMIA">
<span>#Html.LabelFor(model => model.LastName, "გვარი")
<br />
#Html.EditorFor(model => model.LastName)
</span>
<div class="fieldNameInnerForMIA">
<span>#Html.LabelFor(model => model.FirstName, "სახელი")
<br />
#Html.EditorFor(model => model.FirstName)
</span>
</div>
</div>
<div class="fieldNameForMIA">
<span>#Html.LabelFor(model => model.PersonalNo, "პირადი ნომერი")
<br />
#Html.EditorFor(model => model.PersonalNo)
</span>
<div class="fieldNameInnerForMIA">
<span>#Html.LabelFor(model => model.DateOfBirth, "დაბადების თარიღი")
<br />
#Html.EditorFor(model => model.DateOfBirth)
</span>
</div>
</div>
<div class="fieldNameForReturnCheckBox">
#Html.LabelFor(model => model.IsIdentified, "სხვა სახელით დაბრუნდა")
#Html.CheckBoxFor(model => model.IsIdentified)
</div>
<div class="saveReturnPerson">
<input type="image" name="submit" id="submit" src="/Content/Resources/SaveGeo.gif" />
</div>
</div>
}
and here is post method which is never called:
[HttpPost]
public ActionResult EditReturnPerson(int id, FormCollection collection)
{ ....
but this method is called when first is loaded:
public ActionResult EditReturnPerson(long parentObjectId, int parentObjectTypeId, bool readOnly = false)
{
....
Mention the method as POST in AjaxOptions
new AjaxOptions { UpdateTargetId = "personListDivforReturnPerson",
HttpMethod ="POST"}
If you do not mention, It will take the Default which is GET.
EDIT : Also If you want to handle it with your own code, You can do it with handwritten JavaScript. Pretty clean and full control.
Get rid of the AjaxBeginForm and use a normal form in your view.
#using(Html.BeginForm())
{
#Html.EditorFor(model => model.FirstName)
#Html.EditorFor(model => model.PersonalNo)
<input type="submit" class="ajaxSubmit" />
}
Now have some javascript to handle the form submit
<script type="text/javascript">
$(function(){
$(".ajaxSubmit").click(function(e){
e.preventDefault();
var item=$(this);
$.post("#Url.Action("EditReturnPerson","YourControllerName")",
item.closest("form").serialize(), function(response){
$("#personListDivforReturnPerson").html(response);
});
});
});
</script>
ბიჭო აქ ვერ გეტყვიან ვერაფერს :D გეუბნები სერვერს მიმართავს და იქ უშლის რაღაცა ხელს. კლიენტის მხარეს ყველაფერი კარგადაა. ეს კიდე მაგარი კაცია, ფორმას უკეთებ სუბმით-ს და default მეთოდი არის პოსტი მაგ დროს.
I found my problem, the problem was [HttpPost] public ActionResult EditReturnPerson(int id, FormCollection collection) { .... in this part, id was int and my id in DB was bigint, so I changed int to long in controller and everything worked, thanks for advice.

Receiving a NullReference Exception error during HttpPost Action when using a ViewModel

I am trying to create what I feel is a very simple form submission using a ViewModel. I have worked on this off and on all day and for some reason cannot understand why when my app gets to my HttpPost action my EmailViewModel is empty. I get a "NullReference Exception Occurred" "Object reference not set to an instance of an object" error.
Can you take a look at my code and tell me where I am being crazy?
Here is my httpPost action:
[HttpPost]
public ActionResult SendStudentAnEmail(EmailViewModel email)
{
Debug.Write(email.Subject); // First NullReferenceException
Debug.Write(email.Body);
Debug.Write(email.Email);
etc. . .
My ViewModel:
namespace MyApp.ViewModels
{
public class EmailViewModel
{
public string Email { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
}
and My View:
#model MyApp.ViewModels.EmailViewModel
#{
ViewBag.Title = "SendStudentAnEmail";
}
<h2>SendStudentAnEmail</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>EmailViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Subject)
#Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Body)
#Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Thank you.
*UPDATE*
If I change my HttpPost Action to use FormCollection, I can use the values just fine, I can even re-cast the FormCollection values back to my EmailViewModel. Why is this?
[HttpPost]
public ActionResult SendStudentAnEmail(FormCollection emailFormCollection)
{
Debug.Write(emailFormCollection["email"]);
Debug.Write(emailFormCollection["subject"]);
Debug.Write(emailFormCollection["body"]);
var email = new EmailViewModel
{
Email = emailFormCollection["email"],
Subject = emailFormCollection["subject"],
Body = emailFormCollection["body"]
};
. . . . then the rest of my code works just how I wanted. . .
Why do I have to cast from FormCollection over to my EmailViewModel? Why isn't it giving me the NullReference Exception if I attempt to simply push an EmailViewModel into my Action?
Your EmailViewModel class has a property called Email of type string. And your controller action takes an argument called email of type EmailViewModel. This confuses the default model binder. So either rename the property inside the view model or the action argument:
[HttpPost]
public ActionResult SendStudentAnEmail(EmailViewModel model)
{
Debug.Write(model.Subject);
Debug.Write(model.Body);
Debug.Write(model.Email);
...
}

Can't add file upload capability to generated MVC3 page

I'm new to MCV and I'm learning MVC3. I created a model and a controller and view was generated for me. The generated code makes perfect sense to me. I wanted to modify the generated view and controller so that I could upload a file when I "create" a new record. There is a lot of good information out there about how to do this. Specifically I tried this: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
The problem is that even when I select a file (not large) and submit, there are no files in the request. That is, Request.Files.Count is 0.
If I create the controller and and view from scratch, in the same project (no model), the example works just fine. I just can't add that functionality to the generated page. Basically, I'm trying get the Create action to also send the file. For example, create a new product entry and send the picture with it.
Example Create view:
#model Product.Models.Find
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Create", "Find", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Find</legend>
<input type="file" id="file" />
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Example Controller:
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0 && Request.Files[0] != null)
{
//Not getting here
}
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(find);
}
This will create the record just fine but there are not files associated with the Request.
I've also tried a controller action like this:
[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
//Not getting here
}
return RedirectToAction("Index");
}
I'm wondering if maybe you can't post a file at the same time as posting form fields? If that is the case, what are some patterns for creating a new record and associating a picture (or other file) with it?
Thanks
Create a ViewModel which has properties to handle your image and Product deatils
public class ProductViewModel
{
public string ImageURL { set;get;}
public string Title { set;get;}
public string Description { set;get;}
}
And in your HTTPGET Action method, return this ViewModel object to your strongly typed view
public ActionResult Create()
{
ProductViewModel objVM = new ProductViewModel();
return View(objVM);
}
And in your View
#model ProductViewModel
<h2>Add Product</h2>
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.Title) <br/>
#Html.TextBoxFor(m => m.Description ) <br/>
<input type="file" name="file" />
<input type="submit" value="Upload" />
#Html.HiddenFor(m => m.ImageURL )
}
Now in your HttpPost action method, accept this ViewModel and File
[HttpPost]
public ActionResult Create(HttpPostedFileBase file, ProductViewModel objVM)
{
if(file==null)
{
return View("Create",objVM);
}
else
{
//You can check ModeState.IsValid if you have to check any model validations and do further processing with the data here.
//Now you have everything here in your parameters, you can access those and save
}
}
You will have to create a ViewModel for Product (maybe ProductViewModel) and add a HttpPostedFileBase field with the same name as the field of the form and use that instead of the Product in the action of the controller.
A ViewModel is nothing but a model used for specific views. Most of the times, with extra data to generate the view or to decompose and form the model on the controller action.
public ProductViewModel
{
public string Cod { get; set; }
// All needed fields goes here
public HttpPostedFileBase File{ get; set; }
/// Empty constructor and so on ...
}

Telerik MVC 3 (Razor) Q1 2012 Editor EditorFor() Binding Returns Null Value and Unobtrusive Validation Doesn't Work

I'm currently working on my first MVC3 application at work (using the Razor view engine), and decided to use the open source Telerik Q1 2012 controls since they will provide a lot of the functionality I need (and look nice as well). Right now the issue I'm having is using the Telerik Editor control and binding to my view model. I have standard Html.EditorFor() controls on the page that return the value in the ViewModel correctly, but the property bound to Telerik Editor is null. Their documentation is completely useless (it only mentions EditorFor one time), and it doesn't seem like they answer too many questions on the forum either. My main question is, how do I bind the Telerik MVC3 Editor to a model and have it set the property that's bound to it? My code for the view model is below (thanks for any help you can provide, and keep in mind, I'm brand new to MVC, I'm doing this project on my own to get familiar with it and introduce some new technologies to the group):
public class SupportViewModel
{
[Display(Name = "Ticket Subject")]
[MaxLength(30)]
[Required(ErrorMessage = "The ticket subject is required.")]
public string TicketSubject { get; set; }
[Display(Name = "Support Issue")]
[Min(1, ErrorMessage = "You must select a support issue.")]
public int SupportIssueID { get; set; }
[Display(Name = "Ticket Priority")]
[Min(1, ErrorMessage = "You must select a ticket priority.")]
public int TicketPriorityID { get; set; }
//public string EmployeeID { get; set; }
public bool IsClosed { get; set; }
[Required(ErrorMessage = "The detail message is required.")]
public string DetailMessage { get; set; }
}
View Code:
#model RadixMVC.ViewModels.SupportViewModel
#{
ViewBag.Title = "Create New Support Ticket";
}
<h2>Radix Support: Create New Support Ticket</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset style="width: 500px">
<legend>Create New Support Ticket</legend>
<div class="editor-label">
#Html.LabelFor(model => model.TicketSubject)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TicketSubject)
#Html.ValidationMessageFor(model => model.TicketSubject)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SupportIssueID)
</div>
<div class="editor-field">
#Html.DropDownList("SupportIssueID", string.Empty)
#Html.ValidationMessageFor(model => model.SupportIssueID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TicketPriorityID)
</div>
<div class="editor-field">
#Html.DropDownList("TicketPriorityID", string.Empty)
#Html.ValidationMessageFor(model => model.TicketPriorityID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsClosed)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IsClosed)
#Html.ValidationMessageFor(model => model.IsClosed)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DetailMessage)
</div>
<div class="editor-field">
#*#Html.EditorFor(model => model.DetailMessage)*#
#Html.ValidationMessageFor(model => model.DetailMessage)
<br />
#{ Html.Telerik().EditorFor(model => model.DetailMessage)
.Name("DetailMessageEditor")
.HtmlAttributes(new { style = "height: 200px" })
.Encode(false)
.Render();
}
</div>
<div>
<br />
<input type="submit" value="Create Ticket" title="Submits a new support ticket" />
<input type="submit" onclick="parent.location='#Url.Action("Index", "Support", "Index")'" value="Cancel" title="Return to Support Home" />
</div>
</fieldset>
}
And finally, Controller Code:
[HttpPost]
public ActionResult Create(SupportViewModel vm)
{
if (ModelState.IsValid)
{
SupportTicket SupportTicket = new SupportTicket()
{
SupportTicketID = Guid.NewGuid(),
EmployeeID = "123456",
TicketOpenDate = DateTime.Now,
TicketModifiedDate = DateTime.Now,
IsClosed = vm.IsClosed,
TicketSubject = vm.TicketSubject,
SupportIssueID = vm.SupportIssueID,
TicketPriorityID = vm.TicketPriorityID
};
TicketDetail TicketDetail = new TicketDetail()
{
TicketDetailID = Guid.NewGuid(),
SupportTicketID = SupportTicket.SupportTicketID,
TicketOrder = 1,
EmployeeID = "123456",
DetailDate = DateTime.Now,
DetailMessage = vm.DetailMessage
};
SupportTicket.TicketDetails.Add(TicketDetail);
db.SupportTickets.Add(SupportTicket);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SupportIssueID = new SelectList(db.SupportIssues, "SupportIssueID", "Name", vm.SupportIssueID);
ViewBag.TicketPriorityID = new SelectList(db.TicketPriorities, "TicketPriorityID", "Name", vm.TicketPriorityID);
return View(vm);
}
I was able to get this working. The documentation is either very outdated or just doesn't explain how to do this very well (probably both). But I was able to get this working by making the following change to my Razor syntax:
<div class="editor-label">
#Html.LabelFor(model => model.DetailMessage)
</div>
<div class="editor-field">
#*#Html.EditorFor(model => model.DetailMessage)*#
#Html.ValidationMessageFor(model => model.DetailMessage)
<br />
#{ Html.Telerik().EditorFor(model => model.DetailMessage)
//.Name("DetailMessageEditor")
.HtmlAttributes(new { style = "height: 200px" })
.Encode(true)
.Render();
}
</div>
Removing the "Name" property from the control solved the problem of not getting anything back, but when I tried to save, I immediately got an error (something to do with XSS, cross-site scripting), and I assumed it was because the HTML wasn't being encoded. I changed the Encode property to true, and now all is good.
Came across a similar thing today.
I was using a View Model and the property I wanted to bind to was was a property of a child object in the View Model.
When I submitted, the value in the RTE was not being bound. When I looked in Request.From object I could see the the value was being returned in the correct format for it to bound in the usual way so I was a little confused.
Anyway, if you want it to bind you need to give the exact name of your property to the the RTE so in your case
.Name("DetailMessage")
should work but
.Name("DetailMessageEditor")
will not.
Im my case i had to name the RTE
.Name("object.Property")
where object is the child object on the View model where my property lives to get it to work
Hope this helps someone.

inconvenient when editing models

I have a problem trying to edit. I work with Areas for better management the application.The problem is in the areas called "Administrator".
Next is the controller code (OfficeControlle), I use a session variable has been previously created and functions to edit the model data I get.
public ActionResult Edit()
{
decimal id;
id = (decimal)Session["consul"];
CAMPUS_UNIVERSITY campus_university = db. CAMPUS_UNIVERSITY.Single(s => s.Idoffice == id);
ViewData.Model = db.OFFICE.Single(c => c.Idoffice == id);
ViewBag.University = db.UNIVERSITY.Single(u => u.IdUniversity == campus_university.IdUniversity);
ViewBag.campus = db.CITY_CAMPUS.Single(u => u.IdCity == campus_university.Idcitycampus);
return View(sede_universidad);
}
[HttpPost]
public ActionResult Edit(CAMPUS_UNIVERSITY campus_university, OFFICE office)
{
if (ModelState.IsValid)
{
db.CAMPUS_UNIVERSITY.Attach(campus_university);
db.ObjectStateManager.ChangeObjectState(campus_university, EntityState.Modified);
db.SaveChanges();
db. OFFICE.Attach(office);
db.ObjectStateManager.ChangeObjectState(office, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.IdCitycampus = new SelectList(db.CITY_CAMPUS, "IdCity", "Name", campus_university.IdCitycampus);
ViewBag.IdConsultorio = new SelectList(db.OFFICE, "Idoffice", "addressoffice", campus_university.Idoffice);
ViewBag.IdUniversidad = new SelectList(db.UNIVERSITY, "IdUniversity", "Name", campus_university.IdUniversity);
return View(campus_university);
}
Next is the view code
#model RolMVC3.Models.CAMPUS_UNIVERSITY
#{
ViewBag.Title = "Edit";
}
<h2>edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<h2> #ViewBag.University.Name - #ViewBag.Campus.Name </h2>
<fieldset>
<legend>OFFICE</legend>
#Html.HiddenFor(model => model.IdUniversity)
#Html.HiddenFor(model => model.IdCitycampus)
#Html.HiddenFor(model => model.Idoffice)
<div class="editor-label">
#Html.LabelFor(model => model.addresscampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.addresscampus)
#Html.ValidationMessageFor(model => model.addresscampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.phonecampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.phonecampus)
#Html.ValidationMessageFor(model => model.phonecampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.emailcampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.emailcampus)
#Html.ValidationMessageFor(model => model.emailcampus)
</div>
<fieldset>
<legend>OTHER DATE</legend>
#Html.Partial("_office", Model.OFFICE)
</fieldset>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("back", "Index")
</div>
The problem appears when I press the "Save" button, get the following error:
The parameters dictionary contains a null entry for parameter 'Id' of non-nullable type ''System.Decimal' ' for method ''System.Web.Mvc.ActionResult Index(System.Decimal)' in ''RolMVC3.Areas.Administrator.Controllers.OfficeController''
When you are redirecting here:
return RedirectToAction("Index");
make sure that you pass the id in the query string as it looks like your Index action requires it as parameter:
return RedirectToAction("Index", new { id = campus_university.IdUniversity });
I'm assuming that your Index action method looks something like this (please correct me if I am wrong):
public ActionResult Index(decimal id)
{
// Your method's code
}
So where you do return RedirectToAction("Index"); you are trying to redirect to an action method that takes no parameters. But in this case there is an action method that requires a parameter, namely id. So when redirecting you need to change your code and supply this id parameter.
This is what you could do:
return RedirectToAction("Index", new { id = /* put your id here */ });

Resources