MVC5 Ajax.BeginForm, UpdateTargetId no render PartialView - ajax

I have a problem with my MVC application.
My controller:
public class CustomerController : Controller
{
CustomerFacade cf = new CustomerFacade();
public ActionResult Create()
{
return View();
}
[HttpPost]
public void Create(Customers customers)
{
if (customers != null)
{
cf.CreateCustomer(customers, UserSession.UserId);
}
// return View();
}
public ActionResult GetAllCustomers()
{
var allCustomers = cf.GetAllCustomers();
return PartialView("InsuranceCustomer", allCustomers);
}
}
My main view:
<div class="x_content">
<div id="mainb" style="height:350px;">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
<i class="fa fa-plus"></i>
</button>
#*render modal*#
#Html.Partial("~/Views/Customer/CreateModal.cshtml")
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
<i class="fa fa-database"></i>
</button>
#*render modal*#
<div id="customerId">
#Html.Action("GetAllCustomers", "Customer")
</div>
</div>
</div>
The partial view CreateModal.cshtml is a form on bootstrap modalpopup:
for example:
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Customer", null, new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "customerId",
OnSuccess = "$('#customerModal').modal('hide')"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-4">
#Html.TextBoxFor(model => model.FirstName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.FirstName })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(model => model.LastName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.LastName })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
// and other field form
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="#Resources.Common.Save" class="btn btn-success" />
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
</div>
and InsuranceCustomer looks like:
#model IEnumerable<Insurance_System.Models.Customers>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
</tr>}
I want to after submiting modal CreateModal loaded again InsuranceCustomer with new element without reloading page.
(sorry for my bad English)

in the controller
public ActionResult Create()
{
return View();
}
[HttpPost]
public void Create(Customers customers)
{
var cust = new customer
{
name=customers.name,
etc....
}
db.customers.add(cust);
db.savechanges();
var listcustomers = db.customers.ToList();
return PartialView("InsuranceCustomer",listcustomers);
}
in the View
<div class="x_content">
<div id="mainb" style="height:350px;">
<div id="customerId">
#*here will be load your partialview*#
</div>
</div>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Customer", null, new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "customerId",
OnSuccess = "$('#customerModal').modal('hide')"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-4">
#Html.TextBoxFor(model => model.FirstName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.FirstName })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.TextBoxFor(model => model.LastName, new { #required = "require", #class = "form-control", placeholder = #Resources.InsuranceCustomer.LastName })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
// and other field form
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="#Resources.Common.Save" class="btn btn-success" />
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
</div>
in the partial view
#model IEnumerable<Insurance_System.Models.Customers>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
</tr>}

Related

how to list dropdown from VIewBag with one to many relation on a partial page?

this is my model.
This is a partial page:
#model FinalForm.Models.Employee
<div class="container">
#using (Html.BeginForm("SaveMarks", "Reg", FormMethod.Post))
{
<div class="form-group">
<button type="button" id="Submit" class="btn btn-info col-md-2" onclick="SubmitM()">Add Marks</button>
<div>
<label class="form-label col-md-1">Qualification</label>
#Html.DropDownList("Quallist", null, "Select", htmlAttributes: new { #class = "form-control search-select offerItem Item border border-dark", id = "Item", #Name = "QualificationList.Q_Name" })
#Html.ValidationMessageFor(model => model.EMP_QUALIFICATION, "", new { #class = "text-danger" })
</div>
<div>
<label class="form-label col-md-1">Marks</label>
<input type="text" id="Marks" name="Marks" class="form-control col-md-1" placeholder="" />
</div>
</div>
}
<div class="panel-body">
<table id="tbl_qlist" class="table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Q_id</th>
<th>Q_Name</th>
<th>Marks</th>
<th>Del</th>
</tr>
</thead>
</table>
</div>
</div>
this is contoller method:
[ChildActionOnly]
public ActionResult Equalify()
{
ViewBag.Quallist = new SelectList(new List<QualificationList>(), "Q_id", "Q_Name");
return PartialView("Equalify");
}
```
System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Quallist'.'

Single model and multiple views

I have a one model with Mymodel it contains the properties like name ,age,contact, phone,address,sortcode ,sysmcode like this and all these are required fields.
I have controller with name Home.
In HomeController i have action methods like
index
Contact(Mymodel model)
Code(Mymodel model)
I have navigate to the index page and provided the details and submitted ,it navigate to the Contact page.
while loading contact page it showing the validation error message.
Try this sample code for you reference. I tested and working fine.
Model Class :
public class Mymodel
{
[Required]
public string Name { get; set; }
[Required]
public string Age { get; set; }
[Required]
public string Contact { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Sortcode { get; set; }
[Required]
public string Sysmcode { get; set; }
}
Home Controller Actions :
public class HomeController : Controller
{
public ActionResult Index()
{
//assigned value for test purposes.
Mymodel tt = new Mymodel()
{
Name = "Dumm",
Age = "55",
Address = "test",
Contact = "46516",
Phone = "516566",
Sortcode = "sdad",
Sysmcode = "asdad"
};
return View(tt);
}
public ActionResult Contact(Mymodel model)
{
ViewBag.Message = "Your contact page.";
return View(model);
}
}
And finally the Views :
Index.cshtml
#model WebApplication1.Models.Mymodel
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Mymodel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Contact, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Contact, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Contact, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Sortcode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sortcode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sortcode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Sysmcode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sysmcode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sysmcode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Contact.cshtml
#model WebApplication1.Models.Mymodel
<div>
<h4>Mymodel</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
#Html.DisplayFor(model => model.Name)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Age)
</dt>
<dd>
#Html.DisplayFor(model => model.Age)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Contact)
</dt>
<dd>
#Html.DisplayFor(model => model.Contact)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Phone)
</dt>
<dd>
#Html.DisplayFor(model => model.Phone)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Address)
</dt>
<dd>
#Html.DisplayFor(model => model.Address)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Sortcode)
</dt>
<dd>
#Html.DisplayFor(model => model.Sortcode)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Sysmcode)
</dt>
<dd>
#Html.DisplayFor(model => model.Sysmcode)
</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List", "Index")
</p>
Validations working fine.
Hope this helps.

Insert and list data in onew View

What I am trying to do is to have one page to create new House and also diplsay all existing houses.
the code for the main view is :
#modelData.Models.SGHouse
#{
ViewBag.Title = "";
}
<h2>Create</h2>
#using (Ajax.BeginForm(new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "HouseList"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SGHouse</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#*<div class="form-group">
#Html.LabelFor(model => model._id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model._id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model._id, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.House, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.House, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.House, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#Html.Partial("_Houses",Model)
The code for my Partial view to list all houses is :
#model IEnumerable<Data.Models.SGHouse>
<div id="HouseList">
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.House)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.House)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item._id }) |
#Html.ActionLink("Details", "Details", new { id = item._id }) |
#Html.ActionLink("Delete", "Delete", new { id = item._id })
</td>
</tr>
}
</table>
</div>
I am not sure what view to return from my controller, if I do :
public ActionResult Create()
{
return View();
}
I get error from my partial view about model is null.
If I use :
public ActionResult Create()
{
return View(new SGHouse());
}
Then I get error
The model item passed into the dictionary is of type 'Data.Models.SGHouse', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Data.Models.SGHouse]'.
Any help how to resolve this.
Thanks
Create one new Property in class like this
public class SGHouse
{
public List<SGHouse> ListSGHouse { get; set; }
}
And in Constroller
public ActionResult Create()
{
SGHouse model = new SGHouse();
List<SGHouse> LstSGHouse = new List<SGHouse>();
LstSGHouse = //Just add list of SGHouse to this property
model.ListSGHouse = LstSGHouse; //Assign above to this
return View(model);
}
In View Just Call like this
#Html.RenderPartial("_Houses", Model.ListSGHouse);
Make Sure to Check model is not null in your partial view
#if (Model != null)
{
}

I'm trying to send two parameters from view to controller but the second is always null

I'm trying to send two parameters (HttpPostedFileBase and the model) from the view to the Create method in the controller but the variable HttpPostedFile photos always gets null values.
Here is the Controller Code:
public async Task <ActionResult> Create([Bind(Include =
"Id,Name,Description")] Models.Environment environment, HttpPostedFileBase photos)
{
if (ModelState.IsValid)
{
if (photos!=null)
{
DataBlobImage dataBlobImage = new DataBlobImage();
environment.Logo = await
dataBlobImage.CreateImage("environment",
environment.Id.ToString(), photos);
}
//Creation date
environment.CreationDate = DateTime.Now;
//Get the creation user ID
environment.CreationUser = 1;
//By default when you create a user is active
environment.Active = true;
db.Environment.Add(environment);
await db.SaveChangesAsync();
return Json(new { success = true });
}
return View(environment);
}
View code:
#using (Html.BeginForm("ModalCreate", "Environment",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-header create-window">
<button type="button" class="close"
data-dismiss="modal" aria- hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Crear nuevo Ambiente</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label for="file">Subir Imagen:</label>
<input id="photos" name="photos" type="file"
style="width: 100%;" />
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Cancelar</button>
<input class="btn btn-primary" type="submit" value="Crear" />
</div>
</div>
</div>
}
I think you don't need to pass an additional parameter for that. You can alway access it like below inside your action method:
HttpPostedFileBase file = Request.Files["NameOfYourFileUploadControl"];
Hope this will help.

how to use role in mvc identity 2.1.0

I want to introduce the identity role to my login page .the user after entering username and password should select a dropdownlist of roles (superuser-admin-user).how could that happen?
Create a class to manage roles, that would be something like ApplicationRoleManager
public class ApplicationRoleManager : RoleManager<IdentityRole, string>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole, string, IdentityUserRole>(context.Get<ApplicationDbContext>()));
}
}
Then you need to create instance of ApplicationRoleManager on owin startup. Add below code inside the ConfigureAuth method on Owin startup. App_Start >> Startup.Auth.cs
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
Now you have all setup for manage your roles. Make sure you have added roles to your 'AspNetRoles' table
Then you can retrieve roles as below inside the Login (Get) action
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
var roles = roleManager.Roles.ToList();
var list = new SelectList(roles, "Id", "Name");
ViewBag.Roles = list;
ViewBag.ReturnUrl = returnUrl;
return View();
}
Then you can get roles in the Login view. After that populate dropdownList with roles. Your rasor script will look like below.
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label id="RoleDdlLabel" class="col-md-2 control-label">Select Role</label>
<div class="col-md-10">
#Html.DropDownList("RoleList", ViewBag.Roles as SelectList)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<p>
#Html.ActionLink("Register as a new user", "Register")
</p>
#* Enable this once you have account confirmation enabled for password reset functionality
<p>
#Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>*#
}
I hope you can finish the saving part by posting the selected role with other model values. You can change the LoginViewModel to include roles.
Hope this helps.

Resources