How to save dynamically added partial view data to database - asp.net-mvc

I have added a feature to add more users information by providing "add another user" link.
This link load a partial view on the page.And when I click save at the end after adding 3 0r 4 user partial view, How can i save this data into database ,
$("#addAnotherUserLink").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$(".userDiv").append(" <div class='userPartialDiv'><a href='#' class='deleteRow'>Delete</a>" + html + "</div>");
}
});
return false;
});
My view derived from a viewmodel -- #model MyApp.DataModels.DemoViewModel
And controller
[HttpPost]
public ActionResult AddUserForm(DemoViewModel demoViewModel)
{
}
But user partial view is loaded dynamically. How to access that partial view model data into controller.
Thanks

Put Users (or DemoViewModel from your controller) view models into List (it can be only one viewmodel, another you will add by javascript) and print it in theview. It will generate inputs with indexes in the name and ID ... something like UsersModels_1_Property. When you are adding new row to your form, you have to to ensure that HTML inputs has right index on name and ID. In "create" action you will receave list of User view model.
Here is very good article about your problem http://www.techiesweb.net/asp-net-mvc3-dynamically-added-form-fields-model-binding/

Related

MVC Moving from one Model View to Another Model View

I am trying to move from one Model's view to another Model's view. I have a Person model and a BurnProject model. From my Person's Index view I have a "Select" link in which I would like for it to go the BurnProject's Index view. I have tried a couple of things neither have worked.
public ActionResult BurnProject()
{
//return View("~/Views/BurnProject.cshtml");
return RedirectToAction("Index", BurnProject);
}
From my Person's Index view I have a "Select" link in which I would
like for it to go the BurnProject's Index view
Why not create a link which navigates to the index action method of BurnProjectsController ?
So in your Person's index view, you may use the Html.ActionLink helper method.
#model Person
<h1>This is persons index view<h1>
#Html.ActionLink("Select","Index","BurnProjects")
This will generate html markup for an anchor tag which has href attribute set to "BurnProjects/Index".
If you want to pass some data from the person's index view to your BurnProject index action, you can use another overload of Html.ActionLink
#model Person
#Html.ActionLink("Select","Index","BurnProjects",new {#id=Model.Id},null)
Assuming your Person entity has an Id property(which you want to pass the value for) and your BurnProjects index action accepts an id param
public ActionResult Index(int id)
{
// return something.
}

Partial View different model

I am trying to use a partial view that uses a different model than the one used in the main view. The partial view has
to show a list with the products recently added. But I am stuck on how and where to implement the logic for retrieving the data I need from the database.
Home/Index.cshtml:
#Html.Partial("~/Views/Shared/_LatestProducts.cshtml", new List<Website.Models.LatestProductsList>())
Shared/_LatestProducts.cshtml:
#model List<Website.Models.LatestProductsList>
#foreach (var item in Model)
{
<a href="#" title="img">
<img src="~/Content/images/latest-product-img.jpg" alt="" /><p>#item.ProductName</p>
</a>
}
And I have the following code that I am trying to use in order to get some products for tests and show them in the partial view:
public PartialViewResult _LatestProducts()
{
List<LatestProductsList> latestProd = (from p in db.Products
where p.ID < 5
select new LatestProductsList { ProductName = p.Title }).ToList();
return PartialView(latestProd);
}
I thought that I might use it in the HomeController, but that obviously doesn't work and I am not sure if partial views should have their own controller, if I can
just call it from another class. I am still wrapping my head around ASP MVC, so any help will be appreciate it.
Just call the action that renders the partial view in Index.cshtml.
#Html.Action("_LatestProducts", "Product")
Second parameter is the name of the controller that has the _LatestProducts method.
Just a reminder: Names with _ prefix is for partial views only, not action methods. You should rename it to LatestProducts.

CRUD, create and update functionality on same view : ASP.net MVC2 + EF

I am a newbie and is making web application in Visual Studio 2010 using MVC2 + Entity framework.
I have a situation in which I want to put both operations i.e create user / update user at same view, I have also tried attaching relevant picture where I have made two portions one for create user and second for manage users.
My 'create user' fields are at top of website and when user click 'create button' page got refreshed and all enlisted users gets displayed on same view under second portion 'manage users' showing link to edit/delete them.
I want that when I click on edit link, that particular entity fields get populated on same view in first portion 'create user' where I can modify them and press 'update button'
VIEW
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%# Import Namespace="MyNamespace" %>
<h4>Create New User</h4>
<form method="post" action="/Lignum/CUser">
<label for="inputEmail3">Full Name</label>
<input type="text" name="Fullname" id="txtFullname" >
<label for="inputEmail3">Email</label>
<input type="email" name="Email" id="Email1">
<button id="btnCUser" class="btn btn-primary">Create</button>
</form>
<h4>Manage Users</h4>
<table>
<tr>
<td>Sr#</td><td>Name</td><td>Email</td><td></td>
</tr>
<% int i=0;
foreach (MyWebsite.Models.User objUser in ViewData.Model as IEnumerable<MyWebsite.Models.User>)
{%>
<tr>
<td><%= ++i%></td>
<td><%= objUser.Fullname%></td>
<td><%= objUser.Email%></td>
<td>
Edit
</td>
</tr>
<%}%>
</table>
CONTROLLER
public ActionResult Index()
{
return View("UserMgt", _repositoryUser.SelectAll());
}
public ActionResult Edit(object Id)
{
if (Id != null && Id.ToString().Trim().Length > 0)
{
int param = int.Parse(Id.ToString());
return View("UserMgt", _repositoryUser.SelectByID(Id));
}
return View("404");
}
You will need to make use of JQuery & Ajax to achieve this. Your page is getting refreshed most likely because your are submitting a form. Instead of form submit, you need to attach a function to handle onclick event.
In that function you will know which item is clicked, load the data to be edited from the server sending an ajax request with item id.
When request return you can then open a JQuery popup window or update page's html to display data. User will be allowed to make changes and on Ok button click you can again send the data back to server to save.
I am looking for an example online to refer to you as my code is little complex. You can also look for an example online.
UPDATE:
i want that when i click on edit link, that particular entity fields
get populated on same view in 1st portion 'create user' where i can
modify them and press 'update button'
Ok, looked at your code. As I said earlier you will need to define an "id" for each html element, the value will be objUser.UserId (you can prefix something if you want). Now define a click event for all html elements i.e. .
For a working example refer this link.
I suggest you progress as you gain some insight and post updated code. We will suggest what's needed for next step. This way you would learn more.
You can try following:
Create a View model with whatever you need on the create page i.e. user details
strongly bind your view with this view model
Have three action methods in controller "Create","Populate" and "Update" with Update and Populate taking Id of the entity as input (you can choose better names)
Initially call Create method which will just return an empty view model with your View
Have a hidden variable in view which will store the Id of the entity (in case of create this will be zero)
on click of create just take the value of this hidden variable and do a post to Update action method.In this case if it is new entity id will be zero
On click of edit go call Populate method with id of the entity which again will return ViewModel with entity details loaded to the same create view (also set the hidden variable with id)
In your update method based on the id perform create or update operation i.e. Create for zero and Update for 1
If you post your code or other details I can give some more details using code.
EDIT: OK few more details in terms of code.
//This is the view model you need to bind to your view
public class UserViewModel
{
public int UserId { get; set; }
public string Email { get; set; }
public string FullName { get; set; }
public List<Users> UserList {get;set;} //For binding to the grid
}
Below are the action methods in controller.
public ActionResult Create()
{
var viewModel = new UserViewModel();
//Logic: Create empty view model for create
return View("UserMgt", viewModel);
}
public ActionResult Edit(int id)
{
var viewModel = new UserViewModel();
//Logic: populate the view model based on the id
return View("UserMgt", viewModel);
}
// Call this method using Jquery ajax
public bool Update(UserViewModel user)
{
if (user.Id == 0)
//Logic : Create the user
else
//Logic : Edit the user
return Json(status); //Status = true if successful else false
}
Initially call create.On click of edit call Edit method.On click of save call Update.
For using jquery ajax follow below link
http://api.jquery.com/jquery.ajax/

Partial Views, redirected to another URL?

Am trying to build a project using MVC 4 and Razor. Am having trouble understand partial views. I have a list of my domain objects that I iterate through and display it in a list box (each row being clickable). I split this into main view and a partial view which renders the domain object which works fine. Inside my partial view I want to make each item clickable and upon click, I want to create a new partial view displaying details about the domain object.
Here is what I have
My main view looks like this
<div class="panely">
<div class="list-group">
#{ Html.RenderPartial("DomainObjectsPartial");}
</div>
</div>
My partial view looks like this
<div class="list">
#foreach (var x in #Model)
{
<a href="#Html.Partial("DomainObjectPartial")" class="list-item">
<em>#x.Name</em>
</a>
}
</div>
I have a view named DomainObjectPartial, which has nothing but a small div with hello.
When the user clicks on a domain object, I expect the partial view to be rendered within the main view, but instead I get a error saying
A potentially dangerous Request.Path value was detected from the
client (<).
And when I look at my URL, the contents of the partial view are contained within it like
http://localhost/<div>hello</div>
I dont want to be redirected to another URL. I just want the partial view to be displayed below the list. Can anyone explain to me what am i missing or not understanding?
I guess you wanted to use AJAX:
<div class="list">
#foreach (var x in Model)
{
<a href="#Url.Action("Index", "Items", new { id = x.Id })" class="ajax-link">
<em>#x.Name</em>
</a>
}
</div>
and then you will obviously have a controller action which will render this partial:
public class ItemsController: Controller
{
public ActionResult Index(string id)
{
// go get the specific item from your database using the id and pass it to
// the partial view
var viewModel = ...
return Partialview("DomainObjectPartial", viewModel);
}
}
and the last part is to AJAXify this anchor:
$(function() {
$('.ajax-link').on('click', function() {
// Send an AJAX call to the server endpoint pointed by the href attribute
// of the anchor and inject the results of this endpoint execution inside a
// DOM element with id="result"
$('#result').load(this.href);
// By returning false you are canceling the default action of the
// anchor click and prevent the browser to redirect to the url pointed
// by the href property. This would leave enough time for your AJAX request
// to execute and return the results.
return false;
});
});
and you will obviously need a DOM element with id="result" somewhere on your page to harbor the results of the AJAX call:
<div id="result"></div>

How to use JQuery Dialog to post sub-set of data on form and refresh parent in MVC?

I have a JQuery dialog which is rendered in a partial view within a main view.
I want the form to post the whole parent page back so it is refreshed on submitting the data. However, the model that I use is stored in a class off the main model class e.g. MainModel.Current
At the top of the dialog I have the link to the MainModel (#model...)
Then in the helpers use lambda like so: m => m.Current.Field
In the controller, the model being passed into the parameter of the function is null?
Is there any reason for this? How do I go about passing in a different model or a subset of the model and refresh the parent.
Its a nightmare in mvc.
Updated
In main view:
#model MyProject.ParentModel
...
Html.RenderAction("AddChildData");
In partial view:
#model MyProject.ParentModel
#Html.TextBoxFor(model => model.ChildData.Name)
#Html.ValidationMessageFor(model => model.ChildData.Name)
In controller:
[HttpPost]
public ActionResult AddItem(ParentModel parentModel)
{
myService.AddItem(parentModel.childData); <-- parentModel is null
return RedirectToAction("Index");
}
Turns out this was because I had a nested form and this was intercepting the model data of the parent form.

Resources