Reputation: 2550
I’m just starting to explore asp mvc and jquery.
I have a simple form that has 2 fields, a Date and an Amount.
The behaviour I am trying to achieve is that when the form is submitted, if the record doesn't already exist in my database then add the item. If it does already exist then warn and ask the user for confirmation. If the user proceeds then overwrite the existing record.
Here is my Mark Up
<% using (Html.BeginForm())
{ %>
<div>
<%:Html.LabelFor(mod => Model.bal.Date) %>
</div>
<div>
<%: Html.TextBoxFor(mod => Model.bal.Date)%>
<%:Html.ValidationMessageFor(mod => Model.bal.Date)%>
</div>
<div>
<%: Html.LabelFor(mod => Model.bal.Amount)%>
</div>
<div>
<%: Html.TextBoxFor(mod => Model.bal.Amount)%>
<%: Html.ValidationMessageFor(mod => Model.bal.Amount)%>
</div>
<p>
<input type="submit" value="Create" />
And here is my controller code
[HttpPost]
public ActionResult Index(Balance bal)
{
var dataContext = new DataDataContext();
if (ModelState.IsValid)
{
// Check if exsists
if (dataContext.Balances.ToList().Contains(bal, new BalanceEquality()))
{
//Exsists, Warn then edit
// Add code here to open popup
// if Continue then over write exsisting data in db
}
else
{
//Not exsist, insert
dataContext.Balances.InsertOnSubmit(bal);
dataContext.SubmitChanges();
}
}
compModel myModel = new compModel();
myModel.bal = bal;
myModel.allBalances = dataContext.Balances.OrderBy(ball => ball.Date).ToList();
return View(myModel);
}
The problem I have is how to display and get the results from a Jquery Popup from within my Controller.
I thought about setting a variable in the ViewData collection, but this didn't seem like "best Practice" to me
Thanks
Upvotes: 0
Views: 3211
Reputation: 2550
I went ahead and implemented the 1st option of the answer.
It would of definitely been easier to stick to the traditional add and edit scenarios, and made use of the standard asp mvc pattern. But it was a good learning experience.
Heres the code and markup, it still needs some more work but you get the idea. Any comments/suggestion would be appreciated.
function validate() {
// Need to do form validation
var balance = {};
balance.date = $("#bal_Date").val();
balance.amount = $("#bal_Amount").val();
$.post("balance/validate"
, balance
, function (data) {
if (data.valid) {
$("#existCheck").val("Valid");
checkBalanceExist();
}
else {
$("#existCheck").val("Not Valid");
$("#errorMessage").text(data.message);
}
}
, 'json'
);
};
function checkBalanceExist() {
$("#existCheck").val($("#bal_Date").val());
// Do ajax call to see if balance exist
var balance = {};
balance.date = $("#bal_Date").val();
balance.amount = $("#bal_Amount").val();
$.post("balance/doesBalanceExist"
, balance
, balanceCheckPost
, 'json'
);
};
balanceCheckPost = function (data) {
$("#existCheck").val(data);
if (data) {
// Does Exist
$("#existCheck").val("Exist");
// raise confirmation popup
$('#dialog').dialog('open');
}
else {
// Does Not Exist
$("#existCheck").val("NOT Exist");
// insert Item
var balance = {};
balance.date = $("#bal_Date").val();
balance.amount = $("#bal_Amount").val();
$.post("balance/insert",
balance,
confirmChange
);
}
};
function overWriteBalance() {
// insert Item
var balance = {};
balance.date = $("#bal_Date").val();
balance.amount = $("#bal_Amount").val();
$.post("balance/edit",
balance,
confirmChange
);
};
confirmChange = function () {
$("#existCheck").val("Changed");
};
and
public JsonResult validate(Balance bal)
{
if (ModelState.IsValid)
{
return Json(new { valid = true });
}
else
{
var errorMessage = "";
foreach (var key in ModelState.Keys)
{
errorMessage += ModelState[key].Errors.FirstOrDefault().ErrorMessage;
}
return Json(new { valid = false, message = errorMessage });
}
}
public JsonResult doesBalanceExist(Balance bal)
{
var dataContext = new DataDataContext();
return Json(dataContext.Balances.ToList().Contains(bal, new BalanceEquality()));
}
public ActionResult Index()
{
var dataContext = new DataDataContext();
compModel myModel = new compModel();
myModel.bal = new Balance();
myModel.allBalances = dataContext.Balances.OrderBy(bal => bal.Date).ToList();
return View(myModel);
}
[HttpPost]
public ActionResult Index(Balance bal)
{
var dataContext = new DataDataContext();
compModel myModel = new compModel();
myModel.bal = new Balance();
myModel.allBalances = dataContext.Balances.OrderBy(ball => ball.Date).ToList();
return View(myModel);
}
public void insert(Balance bal)
{
var dataContext = new DataDataContext();
dataContext.Balances.InsertOnSubmit(bal);
dataContext.SubmitChanges();
}
public void edit(Balance bal)
{
var dataContext = new DataDataContext();
var balToEdit = dataContext.Balances.Single(b => b.Date == bal.Date);
balToEdit.Amount = bal.Amount;
dataContext.SubmitChanges();
}
}
Upvotes: 0
Reputation: 10248
You are at the wrong end of your execution sorry, the Controller is independent of the View i.e. you can't reply to the response during execution of the Controller code other than to return a View. You could do one of at least four things (I am sure there are other solutions):
1 - Use Ajax to make a call to a JsonResult controller method that determines whether the entry already exists after the submit button is clicked - then based no the result of the query you can display a popup whereby "Yes" submits the form and overwrites, or "No" stops the form being submitted.
2 - You can return the view (without submitting the query to the db) and ask the user to confirm overwriting the existing record - but you would have to add some additional logic like a hidden input field in order to determine that the user has seen the message and has agreed to overwrite. This wouldn't be a great approach and probably wouldn't be very intuitive for the user.
3 - Add an "overwrite existing record" checkbox to the form that confirms that the user want's to overwrite the data if it already exists.
4 - Logically seperate Add and Edit for the user so that when a user wants to update an existing record they select the record from a list and edit the existing data - this would be the most traditional method I would think. Then if the user attempts to add a new item that is the same as an existing one you simply re-display the page with an error stating that the record already exists.
Upvotes: 2