How do I pass EditorFor Value to Controller Method - c#

Please assist, I have the following Ajax code
#Ajax.ActionLink(linkText: "Call An Action",
actionName: "GetCoverDate",
routeValues: new { appd = Model.AppDate },
ajaxOptions: new AjaxOptions
{
UpdateTargetId = "ajaxtarget",
InsertionMode = InsertionMode.Replace
})
My Controller Action
public string GetCoverDate(DateTime appd)
{
return appd.AddMonths(6).ToString();
}
What this does is it takes the contents of Model.AppDate and adds 6 months to it via ajax and controller's method and displays the results in a div
I'm trying to have the following changes to the code.
Insert the returned results (date) to the appropriate EditorFor (at
the moment I'm displaying the result in a div - ajaxtarget)
The routeValue as it is, passes a date that was set as default when
the view was loaded, how do I pass the value currently contained on
the EditorFor (in case the user has selected a different date)?
Thank you in advance

Related

Ajax begin form not picking up strong type drop down list value

I am using Ajax begin form for a search page to bring back results. I have the following markup.
#using (Ajax.BeginForm("GetSearchResults",
"MYController",
new
{
siteID = Model.SiteID
},
new AjaxOptions()
{
HttpMethod = "GET",
AllowCache = true,
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "search-reults"
}))
{
#Html_DropDownListFor(model => model.SiteID, Model.StatusCollection)
}
There are a few other strong type textboxes and a submit button on the page. All textboxes submit data back to the controller but the drop down list doesn't. It always submits the default value 0. Are there any other steps I need to do to pick up the value or something in the JQuery onchange event?
Removing the route parameter siteID worked. I do not need to pass strong type control values through as route parameters.

MVC C# PagedList - PagedListPager passing parameters

I have a paged list using unobtrusive ajax that looks like this.
#Html.PagedListPager(Model, page => Url.Action("Images", "Admin", new { imageLibrary = image.ImageLibrary, page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions()
{ InsertionMode = InsertionMode.Replace, UpdateTargetId = "imagesContainer" }))
My controller looks like this:
public ActionResult Images(ImageModels image, int? page, string imageLibrary)
{
// do stuff here
}
I was trying to pass a model to my controller, so instead of imageLibrary = image.ImageLibrary, I should have only needed to pass image = imageModel, but when I pass the model itself, the controller gets a null value (yes the model name was spelled correctly). When I try to get a property of the model and pass it to the controller (that's the imageLibrary = image.ImageLibrary) the controller receives both the model and the imageLibrary string value! This works fine for the end result, I just don't understand why it works, and I shouldn't have to pass the string value imageLibrary to my controller - especially if I'm not really using it.
Any insight on this would be appreciated.

Display Success message on the same page when submit

I'm using Html.Beginform in view page and get the parameters using FormCollection to the controller i want to return the Success message on the same ViewPage as a result.i'm using following code,
public string InsertDetails(FormCollection collection)
{
string result = "Record Inserted Successfully!";
return result;
}
It shows the success message on the new page.How can i resolve this? what i have to return to get the Success message on the same page?
Personally, I'd pop the result string into the ViewBag.
public ActionResult InsertDetails(FormCollection collection)
{
//DO LOGIC TO INSERT DETAILS
ViewBag.result = "Record Inserted Successfully!";
return View();
}
Then on the web page:
<p>#ViewBag.result</p>
I have following Options.
1. Use Ajax Begin Form with AjaxOptions like below
#using (Ajax.BeginForm("ActionName", "ControllerName", new { area = "AreaName" }, new
AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "alert('Success');" //This will execute once the Ajax call is finished.
}, null))
{
<input type="submit" name="nameSubmit" value="Submit" />
}
2. Use JQuery to Manually Setup the XHR Request
$.ajax({
url: "#Url.Action("ActionName", "ControllerName", new { area = "AreaName" });",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({param : Value})
})
.done(function () { alert('Success');}) //This will execute when you request is completed.
.fail(function () { })
My Suggestions
There are following disadvantages while using the FormCollection
Point - 1
In case FormCollection is being used...It will be mandatory to Type Cast the Primitive Type Values un-necessarily because while getting the entry of specific Index of the System.Collections.Specialized.NameValueCollection, value being returned is of type String. This situation will not come in case of Strongly Typed View-Models.
Issue - 2
When you submit the form and goes to Post Action Method, and View-Model as Parameter exists in the Action method, you have the provision to send back the Posted Values to you View. Otherwise, write the code again to send back via TempData/ViewData/ViewBag
Point - 3
We have Data Annotations that can be implemented in View Model or Custom Validations.
ASP.Net MVC simplifies model validatons using Data Annotation. Data Annotations are attributes thyat are applied over properties. We can create custom validation Attribute by inheriting the built-in Validation Attribute class.
Point - 4
Example you have the following HTML
<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" />
Question : How can we access the value of customAttr1 from the above eg from inside the controller
Answer : When a form get posted only the name and value of elements are posted back to the server. You can also use Hidden Fields to post the Attributes to Post Action method.
Alternatives : Use a bit of jQuery to get the custom attribute values, and post that along with the form values to action method
Another option is to rather put what you got in your custom attributes in hidden controls
That's the reason, I would always prefer to use View-Models
we can do it on Form inside view
#using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "POST", OnSuccess = "Showmessage" }))
[HttpPost]
public ActionResult Test(TestViewModel model)
{
return Json(new {isok=true, message="Your Message" });
}
function Showmessage(data)
{
$('#Element').html('Successfully Submitted');
}

Get query string from an ajax call

Hi I am trying to get a querystring from an ajax call and it does not seem to work so well.Here is my code:
#Ajax.ActionLink("Add To Cart" ,
"AddToCart" ,
"Products",
new {
ProductId = #products.ElementAt(0).Value
},
new AjaxOptions{
Url = "/Products/AddToCart",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "UpdateCart",
HttpMethod = "GET"
})
Each link I have in my application calls something like this:
Products/AddToCart?ProductId=5
This is the controller it calls:
public ActionResult AddToCart(string ProductId)
{
string ProductCeva = ProductId;
}
Now from what I learned so far about MVC3 I assumed that the parameter ProductId would be 5 in our case , but when I debug the code , I get that it is null.
What am I doing wrong here and how can I get the ProductId query string in this casE?
Remove the Url = "/Products/AddToCart", bit from your AjaxOptions.
Why?
Here's why. The following code:
#Ajax.ActionLink(
"Add To Cart" ,
"AddToCart" ,
"Products",
new {
ProductId = #products.ElementAt(0).Value
},
new AjaxOptions {
Url = "/Products/AddToCart",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "UpdateCart",
HttpMethod = "GET"
}
)
generates:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#UpdateCart" data-ajax-url="/Products/AddToCart" href="/Products/AddToCart?ProductId=5">Add To Cart</a>
Now even if the href of the generated anchor is correct (/Products/AddToCart?ProductId=5) that's not what is used for the AJAX request. The jquery.unobtrusive-ajax.js that you are using and which unobtrusively AJAXifies all anchors uses the data-ajax-url attribute (if present) when sending the AJAX request instead of the href attribute. Now look at the value of the data-ajax-url attribute and you will understand why you get null in your controller action.
You would also have seen this if you had used FireBug or a similar javascript debugging tool because when you would have inspected the Network tab to see why your AJAX request is not working you would have seen the wrong url being used.
Long story short two things to remember from this question (the first being more important as it allows you to deduce the second):
Use FireBug
the Url property of the AjaxOptions allows you to override the url to be used when sending the AJAX request.

Asp.net MVC 2: Can Ajax.ActionLink pass a parameter without it going into the url?

I have the following in partial view
<%= Ajax.ActionLink("Plunder Again", "Resources", new { controller = "Resource", parent = Model.ToJson() }, new AjaxOptions { UpdateTargetId = Model.ResourceType })%>
going to the controller method:
public ViewResult Resources(/*ModelResource parent*/)
{
Debug.Assert(Request.Params["parent"]!=null);
var jss=new System.Web.Script.Serialization.JavaScriptSerializer();
var parent=jss.Deserialize<ModelResource>(Request.Params["parent"]);
return View(parent.PlunderAmount);
}
but it throws an exception because the json doesn't properly pass via url, it can't find the 'Type' parameter.
I tried simply having the ModelResource as a parameter to the Action but it came in as null
This action will also be returning a partial view if that matters in any way.
ActionLink is used to create an anchor to a URL -- the URL must be valid! In general, you don't pass a whole object to an Action because the route values have to be bound back into the model and passed to the action. You might pass an ID of object though so the Action can get the object using that key.
If you want to send Model to controller instead of Ajax.ActionLink use Ajax.BeginForm

Categories

Resources